Page 157 - Introduction to Programming with Java: A Problem Solving Approach
P. 157
(i.e., each case label) is limited to an exact match with an int or char constant. With an if statement, each test can be a full-blooded expression, complete with operators, variables, and method calls.
In a nutshell, when you need to do one thing from a list of multiple possibilities:
• Use a switch statement if you need to match an int or char value.
• Use an if statement if you need more flexibility. 4.8 while Loop
There are two basic categories of control statements—forward branching statements and looping statements. The if statement and switch statement implement forward branching functionality (so named because the decisions cause control to “branch” to a statement that is ahead of the current statement). The while loop, do loop, and for loop implement looping functionality. We describe the while loop in this section and the do and for loops in the next two sections. But first an overview of loops in general.
4.8 while Loop 123
In solving a particular problem, one of the first and most important things to think
about is whether there are any repetitive tasks. Repetitive tasks should normally be imple-
mented with the help of a loop. For some problems, you can avoid a loop by implementing
the repetitive tasks with consecutive sequential statements. For example, if you are asked
Don’t duplicate code. Use a loop.
to print “Happy Birthday!” 10 times, you could implement a solution with 10 consecutive print statements.
But such a solution would be a poor one. A better solution is to insert a single print statement inside a loop
that repeats ten times. The loop implementation is better because it’s more compact. Also, updating is easier
and safer because the updated code appears in only one place. For example, if you need to change “Happy
Apago PDF Enhancer
Birthday!” to “Bon Anniversaire!” (happy birthday in French), then it’s only a matter of changing one print statement inside a loop rather than updating 10 separate print statements.
while Loop Syntax and Semantics
Now let’s look at the simplest kind of loop, the while loop. Figure 4.10 shows the syntax and semantics of the while loop. The syntax for the while loop looks like the syntax for the if statement except that the word while is used instead of the word if. Don’t forget the parentheses around the condition. Don’t forget the braces, and don’t forget to indent the subordinate statements they enclose.
while (<condition>)} header
false
<condition> true
<statement(s)>
{
⎫ <statement(s)> ⎬
} // end while ⎭
body
Figure 4.10 Syntax and semantics for the while loop