在tic-tac-toe中引发异常

时间:2013-08-18 23:41:49

标签: java nullpointerexception tic-tac-toe

代码的目的是从枚举colour中获取Mark的值。我在setCell类中传递了参数:枚举项,行号,列号到Board方法。

此过程应更改所选单元格的颜色。

我得到了这个例外:

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

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

这是主要课程:

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

}

这是第二节课:

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

}
}

这是枚举的类:

public enum Mark {

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

1 个答案:

答案 0 :(得分:4)

我没有看到任何可能会将gb1设置为除null以外的值的任何代码。也许你的意思是gb?如果是,请删除gb1变量并改为使用gb