Avoiding common programming errors

I have spent the last few weeks helping CMSC 150 students with their labs and programming assignments, and over that time I have seen a number of common mistakes that students make. In these notes I will discuss a number of these common mistakes and give you suggestions for how to avoid them.

Working with variables

The three most common mistakes that come up with variables are

These are all errors that NetBeans will catch for you. If you make any of these mistakes NetBeans will underline your variable in red.

Here are some suggestions for how to avoid these common errors.

Here is an example of the suggested way to declare and initialize a variable.

int ozs = (int) Math.ceil(weight);

Curly brace confusion

Another source of frustrating errors in a program involves curly braces. Many constructs in Java require the use of curly braces, and forgetting a curly brace is a common source of confusing error messages.

My main piece of advice to head off these problems is to

Here are some examples of this. If you are going to write an if statement, start by typing out this:

if() {

} else {

}

This gives you the basic structure of the if statement, and guarantees that you will get the curly braces right from the start. After typing this structure you can go back in and fill in the test and the logic that goes into the if and else parts of the statement.

NetBeans also includes tools to help you structure your code properly so you can see that you have set up the curly braces properly. If you code is getting a bit messy, you can clean it up by doing this:

  1. Select all of your code by doing the Select All command from the Edit menu.
  2. Format your code nicely by doing the Format command from the Source menu.

Chained if-else statements

A common application for if-else statements it to decide which of several possible categories an item falls into. In cases where you have more than two categories to work with, you can use a chained if-else statement to decide.

Here is an example of chained if-else statement from lab three. In lab three we had to decide how to print a particular date given the date number. There are four cases:

  1. The date is less than 1. These dates should not be printed - we print spaces instead.
  2. The date is between 1 and 9. These dates should be printed with an extra space in front.
  3. The date is between 10 and the end of the month. These dates should be printed normally.
  4. The date is after the end of the month. These dates should not be printed - we print spaces instead.

Here is some code you would use to handle this logic.

if(date < 1) {
  System.out.print("   ");
} else if(date < 10) {
  System.out.print("  " + date);
} else if(date <= daysInMonth) {
  System.out.print(" " + date);
} else {
  System.out.print("   ");
}

Working with methods

Writing and calling methods is another source of errors. Here are some things to watch out for when writing and using methods.