0

So pretty much I'm making an array of obvjects called Spots which symbolise the different faces of a dice.

It takes user input (manually set to three for this example), and then creates that make Spots and rolls a random number from 1 to 6.

However when I go to use the rollAgain() method on the aleady created array of Spots I get a null pointer even though I am using the same variable length in both for loops (the one that creates and one that rolls the spots).

My code

Global Variables

private Spots[] spots;

private int x = 3;

Contructor

  public Director(JFrame window, String args[]) {
    JMenuBar menus = new JMenuBar();
    window.setJMenuBar(menus);
    menus.add(makeFileMenu());

    window.getContentPane().add(makePanel(), BorderLayout.WEST);
    window.getContentPane().add(makeSpots(x), BorderLayout.CENTER);

    rollAgain();
}

rollAgain() method

public void rollAgain() {
    int v = 1 + (int) (Math.random() * 6);
    for (int i = 0; i < x; i++) {
        spots[i].setValue(v);
    }
}

makeSpots() method

private JComponent makeSpots(int x) {
    JPanel p = new JPanel();
    p.setBorder(BorderFactory.createTitledBorder("Dice"));

    Spots[] spots = new Spots[x];

    for (int i = 0; i < x; i++) {

        spots[i] = new Spots(200, 200);
        spots[i].setBorder(BorderFactory.createEtchedBorder());
        p.add(spots[i]);
    }
    return p;
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
user1719605
  • 189
  • 1
  • 15

5 Answers5

4

You are setting a local variable

Spots[] spots = new Spots[x];

This doesn't change the field (which happens to have the same name)

private Spots[] spots;

The simplest solution is to not have a local variable

this.spots = new Spots[x];
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You need to instantiate a new Spots array in your constructor.

this.spots = new Spots[x];
Josef E.
  • 2,179
  • 4
  • 15
  • 30
0
spots[i].setValue(v);

Judging from this line, my guess is that the Spot object in the array in null.

The error is in your makeSpots() method. You don't update the value of the field x, but use a local variable. Add this.x = x at the beginning of the method.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
0

In your makeSpots() method, you are creating a new Spots object called spots:

Spots[] spots = new Spots[x];

This effectively hides your private member variable spots from the method. Instead, do this in your makeSpots() method:

spots = new Spots[x];
Edwin Torres
  • 2,774
  • 1
  • 13
  • 15
0

You are declaring a global 'spots' array and then in the makeSpots() you create the spots with a local variable also named 'spots'. Just substitute

Spots[] spots = new Spots[x];

by

spots = new Spots[x];

so the global variable gets a value.

yombo
  • 334
  • 2
  • 5