简体   繁体   English

将元素添加到数组列表时,未知的空指针异常

[英]Unknown Null Pointer Exception when adding an element to an arraylist

What I am trying to do is add an element to an ArrayList each time a method is called. 我想做的是每次调用一个方法时将一个元素添加到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);
}
}

Every time the Roll() method is called, I receive a Null Pointer Error for "totals.add(x3);" 每次调用Roll()方法时,都会收到“ totals.add(x3);”的空指针错误。

Any ideas? 有任何想法吗?

you have totals as static field and you are initializing it in constructor which is called when an instance is created, you need to put it in static initializer block 您拥有总计作为静态字段,并且正在使用创建实例时调用的构造函数对其进行初始化,您需要将其放入静态初始化程序块中

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

inside class body, and when you refer the fields from other class you need to specify class name because it is static fields, or make them non static and access them by creating instance 在类主体内部,并且当您引用其他类的字段时,您需要指定类名称,因为它是静态字段,或者使其成为非静态字段并通过创建实例来访问它们


You should make up your choice: either Roll() is static method or not. 您应该做出选择: Roll()是否为静态方法。 If it is static (as your code suggests) then you need to make sure totals is initialized when you call Dice.Roll() . 如果它是静态的(如您的代码所示),那么您需要确保在调用Dice.Roll()时初始化totals

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);
}
}
if (totals != null) {
    totals.add(x3);
} else {
    totals = new ArrayList<Integer>();
    totals.add(x3);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM