The switch statement: an N-way selection statement.

Slides:



Advertisements
Similar presentations
Pemrograman Dasar Control Flow Statements: Decision Making or Selection PTIIK - UB 1.
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Introduction to Control Statements Presented by: Parminder Singh BCA 5 th Sem. [ Batch] PCTE, Ludhiana 5/12/ Control Statements.
Chubaka Producciones Presenta :.
Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
2012 JANUARY Sun Mon Tue Wed Thu Fri Sat
Declaring Variables You must first declare a variable before you can use it! Declaring involves: – Establishing the variable’s spot in memory – Specifying.
Some basic I/O.
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
Nested conditional statements. A conditional statement (i.e., an if-statement or an if-else- statement) is also a statement We can use an if-statement.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
Shorthand operators.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
The character data type char
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Working with arrays (we will use an array of double as example)
Assignment statements using the same variable in LHS and RHS.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
WORD JUMBLE. Months of the year Word in jumbled form e r r f b u y a Word in jumbled form e r r f b u y a february Click for the answer Next Question.
Mixing integer and floating point numbers in an arithmetic operation.
Chapter 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Integer numerical data types. The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
The while-statement. Syntax and meaning of the while-statement The LOOP-CONTINUATION-CONDITION is a Boolean expression (exactly the same as in the condition.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
The while-statement. The loop statements in Java What is a loop-statement: A loop-statement is a statement that repeatedly executes statements contained.
Object Oriented Programming (OOP) LAB # 1 TA. Maram & TA. Mubaraka TA. Kholood & TA. Aamal.
2011 Calendar Important Dates/Events/Homework. SunSatFriThursWedTuesMon January
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
July 2007 SundayMondayTuesdayWednesdayThursdayFridaySaturday
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Common Mistakes with Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Introduction to Java Import Scanner class to use in our program
Java Language Basics.
CMSC 202 Static Methods.
Common Mistakes with Functions
Starting JavaProgramming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
The Boolean (logical) data type boolean
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
Lecture Notes – Week 2 Lecture-2
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Classes and Objects Static Methods
The for-statement.
2015 January February March April May June July August September
Presentation transcript:

The switch statement: an N-way selection statement

Previously discussed The if-else-statement is a 2-way selection statement The if-else-statement can be used to write a N-way selection statement in Java but the if-else-statement is not intrinsically an N-way selection statement We will now study an intrinsically N-way selection statement: the switch statement

Syntax and meaning of the switch-statement Syntax of the switch-statement: switch ( INT-EXPRESSION ) { case INT-VALUE 1 : STATEMENT 11 ; STATEMENT 12 ;... break; // Marks the end of case INT-VALUE 1 case INT-VALUE 2 : STATEMENT 21 ; STATEMENT 22 ;... break; // Marks the end of case INT-VALUE 2... (more cases if desired)... [default: STATEMENT d1 ; // Optional clause STATEMENT d2 ;... break; ] }

Syntax and meaning of the switch-statement Meaning of the switch statement: The INT-EXPRESSION in the switch statement is first evaluated It INT-EXPRESSION must be an integer valued expression The result of the INT-EXPRESSION is compared to the integer values given in the case clauses

Syntax and meaning of the switch-statement (cont.) If the result of the INT-EXPRESSION is equal to some INT- VALUE in a case clause, the statements following the case clause upto the break statement are executed If the result of the INT-EXPRESSION is not equal to any INT-VALUE in the case clauses, then the statements in the default case are executed if it is specified If the default case is not specified, then the switch statement will terminate without executing any statement.

Syntax and meaning of the switch-statement (cont.) Note: the execution of the switch statement is terminated by: A break; statement, or When execution reaches the end of the switch statement

Syntax and meaning of the switch-statement (cont.) Programming example: translate a numeric month to a string name import java.util.Scanner; public class Switch01 { public static void main(String[] args) { int a; String name = ""; Scanner in = new Scanner(System.in); // Construct Scanner object System.out.print("Enter a numeric month (1-12): "); a = in.nextInt(); // Read in next number into a

Syntax and meaning of the switch-statement (cont.) switch ( a ) { case 1: name = "January"; break; // For brevity, I put case 2: name = "February"; break; // the "break" statement case 3: name = "March"; break; // on the same line. case 4: name = "April"; break; case 5: name = "May"; break; case 6: name = "June"; break; case 7: name = "July"; break; case 8: name = "August"; break; case 9: name = "September"; break; case 10: name = "October"; break; case 11: name = "November"; break; case 12: name = "December"; break; default: name = "Invalid month"; break; // <-- This break statement // is redundant } System.out.println("Name of month = " + name); }

Syntax and meaning of the switch-statement (cont.) Explanation: The INT-EXPRESSION in the switch statement is a Therefore, based on the value of a, one of the cases will be executed When the variable a is equal to 1, the statements: are executed. name = "January"; break;

Syntax and meaning of the switch-statement (cont.) When the variable a is equal to 2, the statements: are executed. And so on. name = “February"; break;

Syntax and meaning of the switch-statement (cont.) If the value of the variable a is not one of the 12 values (1, 2,..., 12) listed in the cases, then the statements of the default case: are executed. name = “Invalid month "; break;

The different integer typed expressions allowed in the switch statement Previously discussed: switch ( INT-EXPRESSION ) <--- must be an integer valued expression {... }

The different integer typed expressions allowed in the switch statement (cont.) The following types are automatically converted into an integer typed value in expressions: Therefore, we can also use them in the switch statement !! byte short char

The different integer typed expressions allowed in the switch statement (cont.) Example: public class Switch02 { public static void main(String[] args) { char x; String name = ""; x = 'C'; switch ( x ) // char is converted to int automatically ! { case 'A': name = "January"; break; case 'B': name = "February"; break; case 'C': name = "March"; break; case 'D': name = "April"; break;

The different integer typed expressions allowed in the switch statement (cont.) case 'E': name = "May"; break; case 'F': name = "June"; break; case 'G': name = "July"; break; case 'H': name = "August"; break; case 'I': name = "September"; break; case 'J': name = "October"; break; case 'K': name = "November"; break; case 'L': name = "December"; break; default: name = "Invalid month"; break; } System.out.println("Name of month = " + name); } This program will compile correctly and run (prints "March").

The different integer typed expressions allowed in the switch statement (cont.) Example Program: (Demo above code) –Prog file: Switch02.java How to run the program: Right click on link and save in a scratch directory To compile: javac Switch02.java To run: java Switch02

The long typed integer expression is not allowed in the switch statement A long typed integer value is not automatically converted to int Therefore, you cannot use a long typed integer value in a switch statement without a casting operation.

The long typed integer expression is not allowed in the switch statement Example: public class Switch03 { public static void main(String[] args) { long a; String name = ""; a = 10; switch ( a ) // Illegal ! { case 1: name = "January"; break; case 2: name = "February"; break; case 3: name = "March"; break; case 4: name = "April"; break; case 5: name = "May"; break;

The long typed integer expression is not allowed in the switch statement (cont.) case 6: name = "June"; break; case 7: name = "July"; break; case 8: name = "August"; break; case 9: name = "September"; break; case 10: name = "October"; break; case 11: name = "November"; break; case 12: name = "December"; break; default: name = "Invalid month"; break; } System.out.println("Name of month = " + name); }

The long typed integer expression is not allowed in the switch statement (cont.) You will get the following compile error: Switch03.java:11: possible loss of precision found : long required: int switch ( a ) ^

String typed values are allowed in the switch statement in Java SE 7 and later... According the the Java development website: switch.html switch.html (This is not the case in Java 6 and other languages such as C/C++) The switch statement in Java version SE 7 and later will also allow String typed expressions (But Java SE 7 has not been released yet)

String typed values are allowed in the switch statement in Java SE 7 and later... (cont.) Example: the following program converts a month name (string) into an integer using a switch statement import java.util.Scanner; public class Switch04 { public static void main(String[] args) { String name = ""; int a; Scanner in = new Scanner(System.in); // Construct Scanner object System.out.print("Enter the name of a month (lower case): "); name = in.next(); // Read in name

String typed values are allowed in the switch statement in Java SE 7 and later... (cont.) switch ( name ) { case "january": a = 1; break; case "february": a = 2; break; case "march": a = 3; break; case "april": a = 4; break; case "may": a = 5; break; case "june": a = 6; break; case "july": a = 7; break; case "august": a = 8; break; case "september": a = 9; break; case "october": a = 10; break; case "november": a = 11; break; case "december": a = 12; break; default: a = 0; break; } System.out.println("Index of month = " + a); }

String typed values are allowed in the switch statement in Java SE 7 and later... (cont.) We cannot compile and run this program because Java SE7 is not yet available !!!

Programming example: convert number grade to letter grade We can use a switch statement to assign a letter grade to a number grade (read from input) Algorithm: We must use integer numeric grade (floating point numbers are not allowed in a switch statement !) Assign letter grade A for numeric grades 90, 91,..., 100 Assign letter grade B for numeric grades 80, 81,..., 89 Assign letter grade C for numeric grades 70, 71,..., 79 Assign letter grade D for numeric grades 60, 61,..., 69 Default: assign letter grade F otherwise.

Programming example: convert number grade to letter grade (cont.) Java program: public class Switch05 { public static void main(String[] args) { int ng; String lg = ""; Scanner in = new Scanner(System.in); // Construct Scanner object ng = in.nextInt(); // Read in next number switch ( ng ) { case 100:.... // I left out a lot of "cases" to save space ! case 90: lg = "A"; break; case 89:

Programming example: convert number grade to letter grade (cont.)... case 80: lg = "B"; break; case 79:... case 70: lg = "C"; break; case 69:... case 60: lg = "D"; break; default: lg = "F"; break; } System.out.println("Letter grade = " + lg); }

Programming example: convert number grade to letter grade (cont.) Example Program: (Demo above code) –Prog file: Switch05.java How to run the program: Right click on link and save in a scratch directory To compile: javac Switch05.java To run: java Switch05