该代码的目的是从枚举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
}
最佳答案
我在任何地方都看不到任何将gb1
设置为除null
以外的值的效果的代码。也许您是说gb
?如果是这样,请删除gb1
变量,而改用gb
。
关于java - 井字游戏引发异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18304715/