Java Reference
In-Depth Information
System. out . println ( "Your grade is between 60 and 69" );
if (s.equals( "F" )) {
System. out . println ( "Your grade is below 60" );
}
}
}
2.6 The switch Statement
It may get tedious to write code that compares a variable to one of several possibilities
using if statements. To simplify the process, Java supports the switch statement. The
rewrite using the switch statement is shown next.
import java . util . ;
public class Grade {
public static void main(String [] args) {
System. out . print ( "Enter letter grade: " );
Scanner keyboard = new Scanner(System. in) ;
String s = keyboard . next () ;
switch (s)
{
case "A" :
System. out . println ( "Your grade is between 90 and 100" );
break ;
case "B" :
System. out . println ( "Your grade is between 80 and 89" );
break ;
case "C" :
System. out . println ( "Your grade is between 70 and 79" );
break ;
case "D" :
System. out . println ( "Your grade is between 60 and 69" );
break ;
case "F" :
System. out . println ( "Your grade is below 60" );
break ;
default :
System. out . println ( "I have no idea what is your grade!" );
}
}
}
The general structure of the switch statement is shown in Figure 2.9. Note that the
default part is optional. In the figure, if the variable is equal to 2, then the control
flow jumps to the line “ case 2: ... ”. Note that this is the only jump that occurs in the
switch statement. After the program jumps to that line, it will continue executing. If there
is nothing to change the control flow again, the program will execute the code for “ case
3: ... ”and“ default: ... ”.
 
Search WWH ::




Custom Search