有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

ArrayList的java空指针异常

我正试图开始学习BlueJ中的Java,但我一直在努力。现在我在看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");
    }
}

但是当我尝试运行“selection”方法,并在弹出窗口中键入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 Exception:Null”

我相信你可以从我说话的方式看出我对Java知之甚少。很明显我做错了什么吗?谢谢所有能帮忙的人


共 (1) 个答案

  1. # 1 楼答案

    您的方法selection未被调用。因此,您的ArrayList为空。对空引用调用方法会导致NullPointerException

    在构造函数中调用该方法

    public TestArrayList()
    {
       selection();
    }