Topic 5: Enumerated Types and Switch Statements

Similar documents
COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

CompSci 125 Lecture 11

Following is the general form of a typical decision making structure found in most of the programming languages:

Java Lectures. Enhancements in Java 1.5

Lecture Set 4: More About Methods and More About Operators

Introduction to Programming Using Java (98-388)

Java is an objet-oriented programming language providing features that support

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Objectives. Describe ways to create constants const readonly enum

Intro to Enums CMSC 202

PROGRAMMING FUNDAMENTALS

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Agenda: Discussion Week 7. May 11, 2009

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

Timing for Interfaces and Abstract Classes

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Structures and Pointers

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Control Structures in Java if-else and switch

Datatypes, Variables, and Operations

Visual Programming. Lecture 3: Loops, Arrays. Mahmoud El-Gayyar

Programming Basics. Digital Urban Visualization. People as Flows. ia

Loops. CSE 114, Computer Science 1 Stony Brook University

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

H212 Introduction to Software Systems Honors

Lec 3. Compilers, Debugging, Hello World, and Variables

Lecture 12. Data Types and Strings

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Bjarne Stroustrup. creator of C++

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

CSC-140 Assignment 6

CS349/SE382 A1 C Programming Tutorial

Introduction to Computers and Programming

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

CS 211: Methods, Memory, Equality

if Statement Numeric Rela5onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

22c:111 Programming Language Concepts. Fall Types I

Object-Oriented Programming

if Statement Numeric Rela7onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Control Structures in Java if-else and switch

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Expressions & Flow Control

Lecture 8 CSE11 Fall 2013 While Loops, Switch Statement, Simplifying Conditionals

Introduction to Computing Lecture 05: Selection (continued)

Lecture Set 4: More About Methods and More About Operators

Java Application Development

CS 302: INTRODUCTION TO PROGRAMMING IN JAVA. Chapter 5: Methods. Lecture 10

Flow of Control: Loops. Chapter 4

AP Computer Science Unit 1. Programs

Motivation. Each distinct type needs its own I/O library INTEGER FLOAT CHARACTER BOOLEAN. Using pure numbers, we can write nonsense:

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

CS171:Introduction to Computer Science II

Chapter 3. Ch 1 Introduction to Computers and Java. Selections

CS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

CS111: PROGRAMMING LANGUAGE II

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

8. Decision-Making Statements. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Research Group. 3: Loops, Arrays

Java Flow of Control

Control Flow Statements

CMSC 104 -Lecture 11 John Y. Park, adapted by C Grasso

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 3: Operators, Expressions and Type Conversion

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CS2141 Software Development using C/C++ C++ Basics

Lec 7. for loops and methods

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Another IS-A Relationship

Chapter 8: A Second Look at Classes and Objects

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

ECE 122. Engineering Problem Solving with Java

CS313D: ADVANCED PROGRAMMING LANGUAGE

Selected Java Topics

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Computer Programming, I. Laboratory Manual. Final Exam Solution

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

CS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Transcription:

Topic 5: Enumerated Types and Switch Statements Reading: JBD Sections 6.1, 6.2, 3.9 1

What's wrong with this code? if (pressure > 85.0) excesspressure = pressure - 85.0; else safetymargin = 85.0 - pressure;! "Magic Numbers" make code hard to read and maintain.! Better: double MAXPRESSURE = 85.0; if (pressure > MAXPRESSURE) excesspressure = pressure - MAXPRESSURE; else safetymargin = MAXPRESSURE - pressure; 2

Constants! "Constants" are a good way to avoid magic numbers! A constant is like a variable that does not vary! Declare a constant whenever:! A number is used more than once in a program! It represents something that does not change! Declare constants inside a class but not inside a method.! Convention: name of constants are all-upper-case! Use the keywords static final static final double MAXPRESSURE = 85.0; static final int SIZE = 100; static final String US = "United States"; 3

Sets of related constants! Suppose that the state of a machine could be running, waiting, or stopped.! It's inefficient to represent these states as Strings! You could represent them as constant integers: static final int RUNNING = 1; static final int WAITING = 2; static final int STOPPED = 3;! But consider a method that wants a machine state for its parameter: hourlycost(int x)! There's nothing to prevent this call: hourlycost(5) 4

A Safer Approach! Define a type with only three values: enum MachineState { RUNNING, WAITING, STOPPED ;! Define methods that take parameters of this type: static double hourlycost(machinestate s)! Call the method using symbolic names for arguments: hourlycost(machinestate.running)! Now the compiler can ensure that the method will get a valid argument hourlycost(5) Error because 5 is not a MachineState 5

Enumerated Types! Enumerated types are:! A new feature in Java 5.0! A simple kind of user-defined type! Used to restrict a type to a finite set of values! Examples: enum MachineState { RUNNING, WAITING, STOPPED ; enum Size { SMALL, MEDIUM, LARGE ; enum Season { WINTER, SPRING, SUMMER, FALL ; enum Suit { SPADES, HEARTS, DIAMONDS, CLUBS ; enum Answer { YES, NO, MAYBE ; enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY ; 6

Enumerated Types! Declaring an enumerated type enum Season { WINTER, SPRING, SUMMER, FALL ;! Declaration may be either inside a class or outside (But a few people have reported problems with DrJava when declaring an enum type that is not inside a class.)! Using an enumerated type Season s; s = Season.SUMMER; System.out.println(s); // prints SUMMER! Advantages of enumerated types Prefix required!! Type safety! Self-documenting code! Prints a readable name (unlike a static final int) 7

Operations on Enumerated Types! OK: assignment, equality-comparison = ==!=! Examples: mycolor = Color.RED today == Day.TUESDAY! Not OK: arithmetic, inequality-comparison + - * / > >= < <=! Examples: Day.MONDAY + Day.TUESDAY Season.WINTER > Season.SPRING 8

Enumerated types are passed by value static double hourlycost(machinestate s) { s = MachineState.STOPPED; return 47.00; public static void main(string[] args) { MachineState x = MachineState.RUNNING; double cost = hourlycost(x); System.out.println(x); // Still RUNNING 9

The values() method! Every enumerated type has a values() method that returns an array of all the enumerated values enum Season { WINTER, SPRING, SUMMER, FALL ;! Season.values() returns an array containing all the values of the Season type Season[] s = Season.values(); // s.length is 4 // s[0] is Season.WINTER // s[1] is Season.SPRING // s[2] is Season.SUMMER // s[3] is Season.FALL 10

Iterating over an Enumerated Type! Use values() to get an array of values! Use a "for-in" loop to iterate over this array. enum Season { WINTER, SPRING, SUMMER, FALL ; for (Season s: Season.values()) { System.out.println("I love Paris in the " + s);! Prints: I love Paris in the WINTER I love Paris in the SPRING I love Paris in the SUMMER I love Paris in the FALL 11

Branching on an Enumerated Type! One way to handle several enumerated cases: enum Season { WINTER, SPRING, SUMMER, FALL ; Season s = someseasonexpression; if (s == Season.WINTER) { heating = true; cooling = false; thermostat = 68.0; else if (s == Season.SUMMER) { heating = false; cooling = true; thermostat = 78.0; else { heating = false; cooling = false; 12

The switch statement: a new way of branching enum Season { WINTER, SPRING, SUMMER, FALL ; Season s = someseasonexpression; switch(s) { case WINTER: heating = true; cooling = false; thermostat = 68.0; case SUMMER: heating = false; cooling = true; thermostat = 78.0; default: heating = false; cooling = false; 13

A switch statement is like a stack of if's if (s == T.CASE1) { handlecase1(); else if (s == T.CASE2) { handlecase2(); else { handleothers(); switch(s) { case CASE1: handlecase1(); case CASE2: handlecase2(); default: handleothers(); 14

More about the switch statement! Valid types for the expression in the switch-clause:! an enum type (Day, Season, etc.)! int! a primitive type that can be converted to int by a widening conversion (short, char, or byte)! Don't forget a break after each case! Values in the case-clauses must be constants (evaluated at compile-time)! OK: 47, SUMMER! Not OK: myage, thisseason, x + y! Default clause is optional! If no matching case or default, switch takes no action 15

! Inside a switch, you must not prefix the enum values with their typename. (Why not?) enum Suit { SPADES, HEARTS, DIAMONDS, CLUBS ; switch(trump) { case SPADES: handlespades(); Suit.HEARTS case HEARTS: is not OK here handlehearts(); case DIAMONDS: handlediamonds(); case CLUBS: handleclubs(); default: System.out.println("Invalid trump suit"); 16

Why does a switch require breaks?! Sometimes you may want to "double up" cases: static boolean weekend(day today) { boolean answer; switch(today) { case SATURDAY: case SUNDAY: answer = true; default: answer = false; return answer;! Note that if there is no break, execution falls through from one case to the next 17

Why does this method fail to compile? enum Temp {HOT, COLD; static String drink(temp t) { String drink; switch(t) { case HOT: drink = "Coffee"; case COLD: drink = "Beer"; return drink; Error: Variable drink might not have been initialized. 18

This version compiles with no errors enum Temp {HOT, COLD; static String drink(temp t) { String drink; switch(t) { case HOT: drink = "Coffee"; default: drink = "Beer"; return drink; Moral: default clauses are a good thing. 19