Question: Pick a switch statement from the reading. Put it into a main() Java program and make it work. Attach the .java file and copyAndPaste the
Pick a switch statement from the reading. Put it into a main() Java program and make it work.
- Attach the .java file and
- copyAndPaste the output into the WriteSubmissionBox
The switch Statement
S1.51
Multiway if-else statements can become unwieldy when you must choose from among many possible courses of action. If the choice is based on the value of an integer or character expres- sion, the switch statement can make your code easier to read.
The switch statement begins with the word switch followed by an expression in parenthe- ses. This expression is called the controlling expression. Its value must be of type int, char, byte, short, or String. The switch statement in the following example determines the price of a ticket according to the location of the seat in a theater. An integer code that indicates the seat location is the controlling expression:
int seatLocationCode;
case 1: System.out.println("Balcony."); price = 15.00; break;
case 2: System.out.println("Mezzanine."); price = 30.00; break;
case 3: System.out.println("Orchestra."); price = 40.00; break;
default: System.out.println("Unknown ticket code."); break;
} // end switch
The switch statement contains a list of cases, each consisting of the reserved word case, a constant, a colon, and a list of statements that are the actions for the case. The constant after the word case is called a case label. When the switch statement executes, the controlling expres- sionin this example, seatLocationCodeis evaluated. The list of alternative cases is searched until a case label that matches the current value of the controlling expression is found. Then the action associated with that label is executed. You are not allowed to have duplicate case labels, as that would be ambiguous.
If no match is found, the case labeled default is executed. The default case is optional. If there is no default case, and no match is found to any of the cases, no action takes place. Although the default case is optional, we encourage you to always use it. If you think your cases cover all the possibilities without a default case, you can insert an error message or an assertion as the default case. You never know when you might have missed some obscure case.
Notice that the action for each case in the previous example ends with a break statement. If you omit the break statement, the action just continues with the statements in the next case until it reaches either a break statement or the end of the switch statement. Sometimes this feature is desirable, but sometimes omitting the break statement causes unwanted results.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
