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