Java Reference
In-Depth Information
Figure 3.2
Sample outputs of the StudentGrade program.
In the StudentGrade program, exactly one of the if/else blocks must exe-
cute. Notice that if the value of score is, say, 92, all the if statements are true;
however, because they are checked in order, the (x >= 90) block will be checked
first, which is true. The grade will be assigned as 'A', the message “Way to go!”
will be displayed, and the flow of control will jump out of the if/else structure.
The next line of code to execute will be the println() statement displaying
“Your grade is a A,” and none of the subsequent Boolean expressions will be
checked.
Notice the truth logic in the if/else control structure of the StudentGrade
program. You might ask why I checked for the score greater than or equal
to 70 and less than 80.
Well, to be honest, I did not need to check for the score to be less than
80. I added that to make you think about the logic and bring attention to
the fact that I already knew score was less than 80 by the time I got there.
If x is not less than 80, it must be greater than or equal to 80, and one of
the two previous Boolean expressions would have evaluated to true.
That being said, having the less than 80 in the expression might make the
code more readable, even though it is not needed.
The switch Statement
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case , and the variable being switched on is
checked for each case.
The syntax for a switch statement looks similar to the following:
switch( variable )
{
case value :
//Statements
Search WWH ::




Custom Search