0

So I'm getting a NullPointerException at Container.add so I'm obviously missing something I just don't see it. ArrayList is of Cell which extends JButton. The method init() is in an extended JPanel class. This is my frist question so be harsh on question format if I'm doing it wrong, Thank you.

    public void init() {
    int k = cells.length / 2;
    for (int i = 0; i < (cells.length / 2); i++) {
        int ID = rand.nextInt(25);
        cells[i] = new Cell(this, ID);
        cells[i + k] = new Cell(this, ID);
        k--;
        cellList.add(cells[i]);
        cellList.add(cells[i + k]);
    }

    Collections.shuffle(cellList);

    for (Cell cell : cellList) {
        add(cell);
    }
}
2
  • 1
    Also, something I noticed is that people don't seem to use debuggers anymore nowadays do they? I mean this was an obvious error, which easily can be overseen after long hours in front of the screen but debugging the code would have revealed the mistake in an instant. So please learn about debuggers and how to use them. Commented Feb 23, 2012 at 19:59
  • You're right. I'm new to programming and overlook the debugger frequently. I'm getting more familiar with NetBeans and it's debugger now. Commented Feb 28, 2012 at 3:55

3 Answers 3

3

Plain and simple don't k-- before cellList.add(cells[i+k])

Even though I don't see what your are doing with the array anyways.

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

Comments

1

What if cells.length is odd (not divisionable by 2, like 3, 5, 7, 15)

Consider that cells.length=5, then k=2 and cells[4] will remain null.

1 Comment

valid point, but shouldn't matter since he wouldn't add cells[4] to cellList
0

You're deprecating k before you add cells[i+k] to the cellList. As a result, cells[i+k] hasn't been initialized yet. Try changing it to:

    cellList.add(cells[i]);
    cellList.add(cells[i + k]);
    k--;

1 Comment

Whoops, was trying to bang out a quick answer before I left work and forgot to modify the original code after I copied and pasted. Sorry about that, answer edited.

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.