Some wise soul once said, "The only people who never make mistakes are the people who never do anything at all." If you're into object-oriented programming, you know all about the agony you can experience with your applets and applications. Here are a few stumbling blocks to step around.
Java is a case-sensitive language, so you really have to mind your Ps and Qs — along with every other letter of the alphabet. Here are some things to keep in mind as you create Java programs:
When you compare two values with one another, you use a double equal sign. The line
if(inputNumber=randomNumber)
is correct, but the line
if(inputNumber=randomNumber)
Here's a constructor for a Java frame.
public SimpleFrame()
{
Button b = new Button("Thank you...");
setTitle("...Jill Byus Schorr");
setLayout(new FlowLayout());
add(b);
b.addActionListener(this);
setSize(300,100);
show();
}
Whatever you do, don't forget the call to the add method. Without this call, you go to all the work of creating a button, but the button doesn't show up on your frame.
Look again at the previous section's code to construct a SimpleFrame. If you forget the call to addActionListener, then when you click the button, nothing happens. Clicking the button a second time and clicking it harder don't help.
When you define a constructor with parameters, as in
public Temperature(double number)
then the computer no longer creates a default parameterless constructor for you. In other words, you can no longer call
Temperature roomTemp = new Temperature();
unless you explicitly define your own parameterless Temperature constructor.
If you try to compile the following code, you get an error message.
public class WillNotWork
{
String greeting = "Hello";
public static void main(String args[])
{
System.out.println(greeting);
}
}
You get an error message because main is static, but greeting isn't static.
When you declare an array with ten components, the components have indices 0 through 9. In other words, if you declare
int guests[] = new int[10];
then you can refer to the guests array's components by writing guests[0], guests[1], and so on, all the way up to guests[9]. You can't write guests[10], because the guests array has no component with index 10.