未知空指针将元素添加到arraylist时出现异常

时间:2014-11-16 06:33:00

标签: java arraylist

我想要做的是每次调用方法时都向ArrayList添加一个元素。

public class Dice
{
private static int x3;
private static ArrayList<Integer> totals;

public Dice()
{
totals = new ArrayList<Integer>();
}

public static void Roll()
{
int x1 = (int)(Math.random()*6)+1;
int x2 = (int)(Math.random()*6)+1;
x3 = x1 + x2;
totals.add(x3);
}
}

每次调用Roll()方法时,我都会收到“totals.add(x3);”

的空指针错误

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

你有总计作为静态字段,并且你在构造函数中初始化它,在创建实例时调用它,你需要将它放在静态初始化程序块中

static {
    totals = new ArrayList<Integer>();
}

在类体内部,当你从其他类引用字段时,你需要指定类名,因为它是静态字段,或者使它们非静态并通过创建实例来访问它们


答案 1 :(得分:0)

您应该做出选择:Roll()是否为静态方法。如果它是静态的(如代码所示),则需要确保在调用totals时初始化Dice.Roll()

class Dice
{
private static int x3;
private static ArrayList<Integer> totals=new ArrayList<Integer>();


public static void Roll()
{
int x1 = (int)(Math.random()*6)+1;
int x2 = (int)(Math.random()*6)+1;
x3 = x1 + x2;
totals.add(x3);
}
}

答案 2 :(得分:0)

if (totals != null) {
    totals.add(x3);
} else {
    totals = new ArrayList<Integer>();
    totals.add(x3);
}
相关问题