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.
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);
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:
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:
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(" "); }
Writing and calling methods is another source of errors. Here are some things to watch out for when writing and using methods.