1

代码的目的是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
}
4

1 回答 1

4

我在任何地方都看不到任何可以设置gb1为除null. 也许你的意思是gb?如果是这样,请删除该gb1变量并gb改用。

于 2013-08-18T23:43:51.597 回答