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?

  • 1
    In the code you posted, `Roll()` is not inside of the class `Dice`. – takendarkk Nov 16 '14 at 06: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? – Elliott Frisch Nov 16 '14 at 06:37
  • Fixed it, that was just an error when i retyped it, not the actual problem, thanks. – user2594218 Nov 16 '14 at 06:38

3 Answers3

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


Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
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);
}
}
Xline
  • 804
  • 5
  • 13
0
if (totals != null) {
    totals.add(x3);
} else {
    totals = new ArrayList<Integer>();
    totals.add(x3);
}
prsmax
  • 223
  • 1
  • 7