70 likes | 146 Views
int gradeLevel = kbd.nextInt (); // can be byte or short also, but not long switch ( gradeLevel ) { // examine value of gradeLevel case 1 : System.out.print ("Go to the Gymnasium"); break; case 2 : System.out.print ("Go to the Science Auditorium"); break;
E N D
intgradeLevel= kbd.nextInt(); // can be byte or short also, but not long switch( gradeLevel ) { // examine value of gradeLevel case1:System.out.print("Go to the Gymnasium"); break; case2:System.out.print("Go to the Science Auditorium"); break; case3:System.out.print("Go to Harris Hall Rm A3"); break; case4:System.out.print("Go to Bolt Hall Rm 101"); break; } This statement is executed if the gradeLevel is equal to 4. This statement is executed if the gradeLevel is equal to 1. The switch statement SE-1020Dr. Mark L. Hornick
The Switch expression is an arithmetic expression that evaluates to an integer value switch ( gradeLevel ) { case 1:System.out.print( "Go to the Gymnasium" ); break; case 2:System.out.print( "Go to the Science Auditorium" ); break; case 3:System.out.print( "Go to Harris Hall Rm A3" ); break; case 4:System.out.print( "Go to Bolt Hall Rm 101" ); break; } Case Label Colon Case Body The switch statement consists of a switchcontrol expression and one or more case statements SE-1010Dr. Mark L. Hornick
true N == 1 ? x = 10; false break; true N == 2 ? switch ( N ) { case 1: x = 10; break; case 2: x = 20; break; case 3: x = 30; break; } x = 20; false break; true N == 3 ? x = 30; false break; Thebreakstatements cause the switch to terminate SE-1010Dr. Mark L. Hornick
true N == 1 ? x = 10; false switch ( N ) { case 1: x = 10; case 2: x = 20; case 3: x = 30; } true N == 2 ? x = 20; false true N == 3 ? x = 30; false A switch without break statements will not terminate after the case is handled The flow will first start from the matching case body and then proceed to the subsequent case bodies. SE-1010Dr. Mark L. Hornick
switch (ranking) { case 10: case 9: case 8: System.out.print("Master"); break; case 7: case 6: System.out.print("Journeyman"); break; case 5: case 4: System.out.print("Apprentice"); break; default: System.out.print("Input error: Invalid Data"); break; } the defaultblock handles cases not explicitly handled SE-1010Dr. Mark L. Hornick
The variable ranking is a chardatatype switch ( ranking ) { case ‘a’: System.out.print( "Go to the Gymnasium" ); break; case ‘b’: System.out.print( "Go to the Science Auditorium" ); break; case ‘c’: System.out.print( "Go to Harris Hall Rm A3" ); break; case ‘d’: System.out.print( "Go to Bolt Hall Rm 101" ); break; } The switch expression can also be a chardatatype SE-1010Dr. Mark L. Hornick