I'm trying to start learning Java in BlueJ, but I'm struggling quite a lot. At the moment I'm looking at ArrayLists. The following code compiles correctly:
import java.util.ArrayList;
public class TestArrayList
{
public static int colorCode;
public ArrayList<String> selection;
public TestArrayList()
{
}
private void selection()
{
selection = new ArrayList<String>();
{
selection.add("red");
selection.add("yellow");
selection.add("blue");
}
}
public void selectColor(int colorCode)
{
if (colorCode == 1)
System.out.println("You have selected " + selection.get(0) + ", the color of fire!");
if (colorCode == 2)
System.out.println("You have selected " + selection.get(1) + ", the color of electricity!");
if (colorCode == 3)
System.out.println("You have selected " + selection.get(2) + ", the color of water!");
else
System.out.println("Invalid selection");
}
}
But when I try to run the method "selection", and I type 1, 2, or, 3, in the popup window, I get errors. All other values, like 0, 4, 5, 6 work fine. But for 1, 2, and 3, the terminal window displays the following error:
java.lang.NullPointerException
at TestArrayList.selectColor(TestArrayList.java:25)
And the editor highlights the line containing the code "selection.get(0)", and returns the error "java.lang.Null.Pointer Exception: null".
I'm sure you can tell from the way I'm talking that I know very little about Java. Is it obvious what I'm doing wrong? Thanks to anyone who can help.