← Java from Scratch
Lesson 50 of 88 · 10 XP
Debugging
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Debugging is the search for logic errors. Techniques:
- printing intermediate values:
System.err.println("i=" + i + " sum=" + sum);—System.erris a separate stream and doesn't get in the way of the main output; - a small example by hand: run the code on paper for
n = 3and compare with what the program prints; - a debugger in an IDE (IntelliJ IDEA, VS Code): a breakpoint, step-by-step execution, viewing variables;
assert x > 0 : "x must be positive";— a check that works when you runjava -ea.
Common logic errors: "off by one" in loop bounds (< instead of <=), integer division,
comparing strings with ==, mixed-up conditions.
Task. The program should print the sum of the numbers from 1 to n, the average (2 decimal places) and how many of them are even,
but it lies. Find the three logic errors.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.