Search code examples
javanullpointerexceptiontic-tac-toe

Exception thrown in tic-tac-toe


The purpose of the code is to take the value of colour from enumeration Mark. I passed the arguments: enum item, row number, column number to setCell method in the Board class.

This process should change the colour of selected cell.

I get this exception:

Exception in thread "main" java.lang.NullPointerException
at games.BoardGameTester.main(BoardGameTester.java:17)

on line gb1.setCell(Mark.ORANGE,0,1);

Here is the main class:

public class BoardGameTester {

private static Board gb;
private static Board gb1;

public static void main(String[] args) {
    // TODO Auto-generated method stub
     System.out.println("3*3 board for a tic tac toe game");
    gb = new Board(3, 3);
    System.out.println(gb.toString());



    gb1.setCell(Mark.ORANGE,0,1);
}

}

Here is the second class:

public class Board  {

private Cell[][] cells;
public Board(int rows, int columns) {
cells = new Cell[rows][columns];
for( int r = 0; r < cells[0].length; r++ ) {
for (int c = 0; c < cells[1].length; c++) {
cells[r][c] = new Cell(r,c);
}
}
}
public Cell setCell(Mark mark, int row, int column) throws
IllegalArgumentException {
if (cells[row][column].getContent() == Mark.EMPTY)
cells[row][column].setContent(mark);

else throw new IllegalArgumentException("Player already there!");
return cells[row][column];
}
public Cell getCell(int row, int column) {
return cells[row][column];
}
public String toString() {
StringBuilder str = new StringBuilder();
for( int r = 0; r < cells.length; r++ ) {
str.append("|"); 


for (int c = 0; c < cells[r].length; c++) {
switch(cells[r][c].getContent()) {
case NOUGHT:
    str.append("O");
    break;
    case CROSS:
    str.append("X");
    break;
    case YELLOW:
    str.append("Y");
    break;
    case RED:
    str.append("R");
    break;
    case BLUE:
    str.append("B");
    break;
    case GREEN:
    str.append("G");
    break;
    case MAGENTA:
    str.append("M");
    break;
    case ORANGE:
    str.append("M");
    break;
    default: //Empty
    str.append("");
    }
    str.append("|");
    }
    str.append("\n");
    }
    return str.toString();

}
}

Here is the enumerated class:

public enum Mark {

EMPTY, NOUGHT, CROSS, YELLOW, RED, BLUE, GREEN, MAGENTA, ORANGE
}

Solution

  • I don't see any code anywhere that would have the effect of setting gb1 to a value that is anything other than null. Perhaps you meant gb? If so, delete the gb1 variable and use gb instead.