Simple Debugging


Collapse Content

In the previous node, you changed the Circle Class so Circles could be created with all of their instance variables set at a specific position. You can now improve your Picture Class to create a Picture in fewer lines of code.


Task
Update your Picture code to create the same face as before but in fewer lines of code. Each Circle can now be created and set to the correct position and appearance in one line of code.


Debugging
Previously, when you moved the Circles around to create a face, they didn't tell you what position they ended up in. This means you might not know what X and Y positions to use for them in the above task.
Often you will want to examine the variable values of a running program to see what's going on and what's broken. There are a few basic ways to do this:

  • Debugger - A debugger is included with IDEs (including BlueJ) to let you step through code and examine the variable values. We won't cover using an IDE debugger right now, but you can use the visual debugger on Learneroo to debug your challenges. See the video below for more information.
Debugger Video


  • BlueJ Interface - The BlueJ visual interface lets you test out your code by calling methods and inspecting Objects. This can be a quick way to check if your methods are working, but it will require repeated manual testing each time you edit and compile your code.

  • Print statements - A quick way to find out values of your running program is to print them out in your code. To avoid confusing it with actual output, you can use System.err.print instead of System.out.print (or System.err.println to print on a new line). This will print to the Error Output instead of the Standard Output.

In BlueJ, Error output will show up in red on the bottom of the output window. On this website, you can also use Error Output for debugging, and it will show up in a grey box beneath the regular output.


Task
Modify moveHorizontal so it prints the xPosition to the Error output at the end of the method. Now you will be able to view the xPosition whenever moveHorizontal is called. You can also add in error printing to get the value of the Y position.


Often your code will be giving the wrong result and you won't know why. You can use this simple print-debugging technique to check on the values of the variables.

Challenge

As in Trying Out Code, you again need to find the Sum of the Squares. This time sum the square of every other number from a to b, starting with a. For example, sumOtherSquare(1,5) = 12 + 32 + 52 = 35.

The code below almost works, but not perfectly. Can you fix it?
Guideline: To find out what's wrong, use Error Printing.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • Won't spoil it, but if you are stuck it is really, really simple... as in 1 character somewhere.

Contact Us
Sign in or email us at [email protected]