Java Reference
In-Depth Information
char grade = args[0].charAt(0);
switch(grade)
{
case 'A' :
System.out.println(“Excellent!”);
break;
case 'B' :
case 'C' :
System.out.println(“Well done”);
break;
case 'D' :
System.out.println(“You passed”);
case 'F' :
System.out.println(“Better try again”);
break;
default :
System.out.println(“Invalid grade”);
}
System.out.println(“Your grade is a “ + grade);
}
}
Notice that when the grade is an A, the first case statement is true. The string
“Excellent!” is displayed, a break is reached, and the flow of control jumps
down to the statement following the switch.
When the grade is a B, the first case is false, the second case is true, and all
subsequent statements following case B will execute until a break is reached.
Even though the case of a C is false when the grade is a B, the flow of control
falls through, since there is no break between case B and case C.
A similar falling through occurs when the grade is a D, when “You passed”
is displayed and so is “Better try again.”
Figure 3.3
Sample outputs of the CongratulateStudent program.
Search WWH ::




Custom Search