The Conditional Operator and the 'switch' Statement
7. Example
Answer:
No
Rules for switch
Statements
switch
StatementsWe will get to those other rules shortly. Here is the previous example, with more explanation:
double discount; char code = 'B' ; // Usually the value for code would come from data // or from user interaction switch ( code ) { case 'A': discount = 0.0; break; case 'B': discount = 0.1; break; case 'C': discount = 0.2; break; default: discount = 0.3; } System.out.println( "discount is: " + discount ); |
- The
expression
is evaluated.- In this example, the expression is the variable,
code
, which evaluates to the character 'B'.
- In this example, the expression is the variable,
- The case labels are inspected starting with the first.
- The first one that matches is
case 'B'
- The
statementList
aftercase 'B'
starts executing.- In this example, there is just one statement.
- The statement assigns 0.1 to
discount
.
- The
break
statement is encountered which ends thestatementList
. - The statement after the entire
switch
statement is executed.- In this example, that is the
println()
statement
- In this example, that is the
Question 7:
If code is 'W' what is discount?