Java Arena
Step 3 of 4

Print debugging

A crash tells you where to look. A wrong answer doesn't: the program runs to the end and prints something, just not the right thing. Then you need to see what the program actually does, step by step.

The simplest tool is a temporary print that shows the values of variables at an interesting point. This program should add up the numbers from 1 to 5, which is 15:

int sum = 0;
for (int i = 1; i < 5; i++) {
    sum += i;
}
System.out.println("Sum: " + sum);
Output
Sum: 10

10 is wrong, but why? Add a print inside the loop:

int sum = 0;
for (int i = 1; i < 5; i++) {
    sum += i;
    System.out.println("debug: i = " + i + ", sum = " + sum);
}
System.out.println("Sum: " + sum);
Output
debug: i = 1, sum = 1
debug: i = 2, sum = 3
debug: i = 3, sum = 6
debug: i = 4, sum = 10
Sum: 10

Now it's plain to see: the loop stops after 4, so 5 is never added. The condition should be i <= 5. Fix it, run it again, and remove the debug print (or comment it out) once the answer is right.

Some tips:

  • Print a label with each value ("debug: i = " + i), so you know which print you're looking at.
  • Print in the places where the program decides something: inside loops, before and after an if, at the start of a method (its parameters) and just before it returns.
  • Start with one or two prints. If the values are right there, move them later in the program; if they're already wrong, move them earlier.

Your task

Challenge 1 of 3

This program should count how many of the numbers typed are even, until the user types -1. It gives the wrong count. Find the bug (a debug print inside the loop helps), fix it, and make sure no debug prints are left. With the input 4, 7, 10, -1 it prints:

Even numbers: 2

Challenge 2

The method sumBetween(int from, int to) should add up every whole number from from to to, both included. For 3 and 6 that's 3 + 4 + 5 + 6 = 18, but it returns 12. Find the bug and fix it. The check runs System.out.println(sumBetween(3, 6)); and expects:

18

Challenge 3

This program reads two exam scores and should print their average with decimals. For 3 and 4 it prints Average: 3.0 instead of Average: 3.5. Print the values along the way to see where the half goes missing, then fix it. With the input 3 and 4 it prints:

Average: 3.5