February 2014
Beginner
1248 pages
62h 25m
English
Notice the while statement’s block in Fig. 4.10 (lines 23–30). Without the braces, the loop would consider its body to be only the first statement, which adds the grade to the total. The last three statements in the block would fall outside the loop body, causing the computer to interpret the code incorrectly as follows:
while (grade != -1) total = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment counter// prompt for input and read next grade from userSystem.out.print("Enter grade or -1 to quit: ");grade = input.nextInt();
The preceding code would cause an infinite loop in the program if the user did not input the sentinel -1 at line 19 (before the ...
Read now
Unlock full access