我收到一个错误,我并不真正理解为什么。这是一个井字游戏(N×n)个 这里是表类TicTacToe游戏中的ArrayIndexOutOfBounds异常
public class Table {
private int columns;
private int rows;
private int wincells;
private PieceType[][] table;
public Table() {
}
public Table(int rows, int columns, int wins) {
this.columns = columns;
this.rows = rows;
this.wincells = wins;
table = new PieceType[rows][columns];
fillEmpty();
}
public void fillEmpty() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
table[i][j] = PieceType.None;
}
}
}
public PieceType getElement(int i, int j) {
return table[i][j];
}
其getElement()方法给予错误后,我调用该函数与 game.move(e.x,e.y);
public void widgetSelected(SelectionEvent e) {
Button button = (Button) e.getSource();
MoveResult moveResult = game.move(e.x, e.y);
if (game.getCurrentPlayer().getPieceType() == PieceType.Cross)
button.setText("x");
else
button.setText("0");
switch (moveResult) {
case ValidMove: {
buttonTable[gridData.horizontalIndent][gridData.verticalIndent]
.setText("X");
game.changePlayer();
}
case WinMatch:
disableButtons();
case Draw:
disableButtons();
}
这是在X和Y获得价值上的问题可能是什么
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j) {
gridData.heightHint = 45;
gridData.widthHint = 45;
Button button = new Button(buttonpanel, SWT.PUSH);
button.setLayoutData(gridData);
button.setData(new Cell(i,j));
buttonTable[i][j] = button;
buttonTable[i][j]
.addSelectionListener(new buttSelectionListener());
什么想法?它来自game.move(e.x,e.y)吗?我没有正确地调用它吗?这里
堆栈跟踪?:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at backview.Table.getElement(Table.java:42)
at backview.Game.move(Game.java:56)
at frontview.MainGui$buttSelectionListener.widgetSelected(MainGui.java:159)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at frontview.MainGui.<init>(MainGui.java:55)
at main.Main.main(Main.java:18)
是调用
if(table.getElement(x, y) != PieceType.None) return MoveResult.InvalidMove;
在哪里/你是如何调用'getElement'方法? – npinti
请发布堆栈跟踪。它显示了问题发生在哪一行。此外,使用默认构造函数可能会导致问题,因为您的字段不会被初始化。提供默认值或不提供默认构造函数是个好主意。 – toniedzwiedz