BETA Try the new lesson view
Code

Finding the bug with the debugger

First decide what should be there. s is the sum of the grades, n is how many grades were typed. Before the loop's first time round, when only one grade has been typed and nothing has been added yet, it should be s = 0 and n = 0.

Check with the debugger

  1. Click in the gutter next to line 7, while (a != 0) {: a red dot.
  2. Shift+F9 (Debug). The program asks for a grade in the Console tab: type 8 and Enter.
  3. The program stops at line 7. In the Variables window:
a = {int} 8
s = {int} 0
n = {int} 1

n is already 1, though not a single grade has been counted yet. Press F8 a few times and watch: after n++, n becomes 2, though only one grade was typed. The counter is always one too big, so it divides by 4, not 3: 27 / 4 = 6.75.

The same bug explains the second symptom too. When 0 is typed straight away, n stays 1, so if (n > 0) is always true, and "No grades." is never printed.

Stop (Ctrl+F2) and remove the breakpoint (click it once more).

Fix it

One line: int n = 0;. Run it with 8, 9, 10, 0:

Average: 9.00

And with just 0:

Grade (0 - stop): 0
No grades.

Commit, and this time the message says what was wrong: Start counter at 0.