Java Reference
In-Depth Information
4. Let's work with one of the more common Java constructs, the for loop. As
mentioned earlier, this is analogous to the PERFORM COBOL verb. Add
these lines to the end of your HelloWorld class:
// Experiment with for and case.
int even = 0, odd = 0, other = 0, total = 0, i;
for (i = 0; i < 9; i++) {
total++;
switch (i) {
case 1:
case 3:
case 5:
case 7:
odd ++;
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 = 4, 4, 1, 9
Look closely at the for loop definition and the output line. How many
times did the for loop execute? What do you think the range of values for
i were as the loop executed?
Search WWH ::




Custom Search