0

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?

3
  • 1
    In the code you posted, Roll() is not inside of the class Dice. Commented Nov 16, 2014 at 6:34
  • Have you considered returning the int result from Roll()? Also, Java method names start with a lower case letter by convention. Finally, why are you initializing your static field in an uncalled constructor? Commented Nov 16, 2014 at 6:37
  • Fixed it, that was just an error when i retyped it, not the actual problem, thanks. Commented Nov 16, 2014 at 6:38

3 Answers 3

2

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


Sign up to request clarification or add additional context in comments.

2 Comments

Agree, there are couple of messes @Stephen
or simply, private static ArrayList<Integer> totals = new ArrayList<Integer>();
0

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

Comments

0
if (totals != null) {
    totals.add(x3);
} else {
    totals = new ArrayList<Integer>();
    totals.add(x3);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.