我想在BlueJ中开始学习Java,但我挣扎了很多。目前我正在查看ArrayLists。下面的代码编译正确:ArrayList的空指针异常
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");
}
}
但是当我尝试运行的方法“选择”,和I型1,2,或3,在弹出的窗口中,我得到的错误。所有其他值,如0,4,5,6都可以正常工作。但是,对于1,2,和3中,终端窗口显示以下错误:
java.lang.NullPointerException
at TestArrayList.selectColor(TestArrayList.java:25)
和编辑器突出了线包含代码“selection.get(0)”,并返回错误“的java.lang .Null.Pointer异常:null“。
我相信你可以从我说话的方式上知道我对Java知之甚少。这显然是我做错了吗?感谢任何能提供帮助的人。
*“但是当我尝试运行方法”选择“”*这不是真的,你调用'selectColor'。 – Tom