简体   繁体   中英

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.

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);"

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. If it is static (as your code suggests) then you need to make sure totals is initialized when you call 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);
}
}
if (totals != null) {
    totals.add(x3);
} else {
    totals = new ArrayList<Integer>();
    totals.add(x3);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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