Completion requirements
Read this chapter, which discusses the switch and '?' operators to write conditional statements. As you read this tutorial, you will learn that sometimes it is better to use a 'switch' statement when there are multiple choices to choose from. Under such conditions, an if/else structure can become very long, obscure, and difficult to comprehend. Once you have read the tutorial, you will understand the similarity of the logic used for the 'if/else' statement, '?', and 'switch' statements and how they can be used alternately.
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?