Java Reference
In-Depth Information
Sample Run 2:
Enter a positive integer: 609321
The sum of the digits = 21
609321 is divisible by 3
609321 is not divisible by 9
Sample Run 3:
Enter a positive integer: 161905102
The sum of the digits = 25
161905102 is not divisible by 3
161905102 is not divisible by 9
5
Choosing the Right Looping Structure
All three loops have a place in Java. If you know or the program can determine in
advance the number of repetitions needed, the for loop is the correct choice. If you do
not know, and the program cannot determine in advance, the number of repetitions
needed, and it could be zero, the while loop is the right choice. If you do not know, and
the program cannot determine in advance, the number of repetitions needed, and it is at
least one, the do...while loop is the right choice.
break and continue Statements
The break and continue statements alter the flow of control in a program. As you have
seen, the break statement, when executed in a switch structure, provides an immediate
exit from the switch structure. Similarly, you can use the break statement in while ,
for , and do ... while loops to immediately exit from these structures. The break
statement is typically used for two purposes:
￿ To exit early from a loop
￿ To skip the remainder of the switch structure
After the break statement executes, the program continues to execute starting at the first
statement after the structure.
Suppose that you have the following declaration:
static Scanner console = new Scanner(System.in);
int sum;
int num;
boolean isNegative;
The use of a break statement in a loop can eliminate the use of certain boolean
variables. The following Java code segment helps illustrate this idea:
 
Search WWH ::




Custom Search