The switch
statement
...
switch(number) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
default: System.out.println("Invalid number " + number); break;
} ...
Enter a weekday number (1=Monday, 2=Tuesday,...) : 6 Saturday
switch(expression) {
[case value_1 :
[statement]*
[break;] ]
[case value_2 :
[statement]*
[break;] ]
...
[case value_n :
[statement]*
[break;] ]
[default:
[statement]*
[break;] ]
}
No. 57
Why “break”?
Q: |
Do we need |
A: |
Figure 154, “Numbers to day's names: The hard way ” can be rewritten as:
Entering a day's number 5 yields: Enter a weekday number (1=Monday, 2=Tuesday,...) : 5 Friday Saturday Sunday Invalid number 5 So the
This time entering a value of 5 again we no longer see Enter a weekday number (1=Monday, 2=Tuesday,...) : 5 Friday Saturday Invalid number 5 Thus fall-through does not depend on numerical |
No. 58
Extending to month days
Q: |
Consider January 2052:
Write an application converting a given day's number within January 2052 (this may be generalized to arbitrary months) to its name e.g.: Enter a day's number:>23 Tuesday TipThe modulo operator “%” is your friend. |
||||||||||||||||||||||||||||||||||||||||||
A: |
With respect to Figure 155, “Better: Using ... switch(day % 7) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; ... case 0: System.out.println("Sunday"); break; } |
String month, season;
...
// Since Java 7: String based case
labels
switch(month) {
case "March": case "April": case "May":
season = "Spring"; break;
case "June": case "July": case "August":
season = "Summer"; break;
case "September": case "October": case "November":
season = "Autumn"; break;
case "December": case "January": case "February":
season = "Winter"; break;
}
}
No. 59
Converting day's names to numbers.
Q: |
Consider the reverse problem to Figure 153, “Converting numbers to day's names ”: We want to map a given day's name to its number as in the following example: Enter a weekday (Monday to Sunday): Friday 5 Issue an error message in case an inappropriate text is being entered: Enter a weekday (Monday to Sunday): July Unknown day name 'July' |
A: |
|
No. 60
Day categories.
Q: |
We want to group working days into categories:
Example execution: Enter a weekday (Monday to Sunday):>Wednesday Midweek TipSometimes omitting |
|||||||||||||
A: |
|
No. 61
Roman numerals, using switch
Q: |
Re-implement Roman numerals using
a switch statement rather then an |
A: |
|