【发布时间】:2014-11-16 06:33:00
【问题描述】:
我要做的是在每次调用方法时向 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);”的空指针错误
有什么想法吗?
【问题讨论】:
-
在您发布的代码中,
Roll()不在Dice类中。 -
您是否考虑过从
Roll()返回int结果?此外,Java 方法名称按照约定以小写字母开头。最后,为什么要在未调用的构造函数中初始化静态字段? -
已修复,只是我重新输入时出现错误,不是实际问题,谢谢。