Java Reference
In-Depth Information
case 7:
odd ++;
for (int i2 = 0; i2 < 10; i2++) {
odd++;
break;
}
break;
case 2:
case 4:
case 6:
case 8:
even ++;
break;
default:
other ++;
break;
}
}
System.out.println ("Odd, Even, Other, and Total = " + odd + ", " +
even + ", " + other + ", " + total);
Compile and rerun the HelloWorld application. The output should look
like this:
...
Odd, Even, Other, and Total = 8, 4, 1, 9
Look closely at the
for
loop definition and the output line. How many times
did the outer
for
loop execute? Why do you think that the variable named
odd
was only incremented once for each execution of the inner loop, even
though the inner loop definition says it should be performed 10 times?
7. For the last exercise, you'll define a labeled
break
. This statement allows
you to go to the end of a code block from inside the code block. Add these
bolded
lines to your HelloWorld class:
// Experiment with for and case.
int even = 0, odd = 0, other = 0, total = 0, i;
outerloop:
for (i = 0; i < 9; i++) {
total++;
switch (i) {