switch Statements
The if
statement in Listing
3.4 makes selections based on a single true
or false condition. There are four cases for computing taxes, which
depend on the value of status. To fully account for all the cases, nested if statements were used. Overuse of nested if statements makes a program difficult to read. Java
provides a switch statement to handle multiple conditions efficiently. You
could write the following switch
statement to replace the nested if
statement in Listing
3.4:
switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(0); }
Figure 3.8. The switch statement checks all cases and executes the statements in the matched case.
This statement checks to see
whether the status matches the value 0,
1,
2,
or 3, in that order. If matched, the corresponding tax is
computed; if not matched, a message is displayed. Here is the full syntax for
the switch
statement:
switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; }
The switch
statement observes the following rules:
-
The keyword break is optional. The break statement immediately ends the switch statement.
Caution
Tip
No comments:
Post a Comment