java - ArrayIndexOutOfBounds Exception in TicTacToe game -
i'm getting error don't realy understand why. tictactoe game(n x n) here table class
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() { (int = 0; < rows; ++i) { (int j = 0; j < columns; ++j) { table[i][j] = piecetype.none; } } } public piecetype getelement(int i, int j) { return table[i][j]; } its getelement() method giving error after call function 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(); } this x , y value
(int = 0; < rows; ++i) (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()); any ideas on problem can be? game.move(e.x, e.y)? not calling properly?
stacktrace?:
exception in thread "main" java.lang.arrayindexoutofboundsexception: 0 @ backview.table.getelement(table.java:42) @ backview.game.move(game.java:56) @ frontview.maingui$buttselectionlistener.widgetselected(maingui.java:159) @ org.eclipse.swt.widgets.typedlistener.handleevent(unknown source) @ org.eclipse.swt.widgets.eventtable.sendevent(unknown source) @ org.eclipse.swt.widgets.widget.sendevent(unknown source) @ org.eclipse.swt.widgets.display.rundeferredevents(unknown source) @ org.eclipse.swt.widgets.display.readanddispatch(unknown source) @ frontview.maingui.<init>(maingui.java:55) @ main.main.main(main.java:18) here method calling
if(table.getelement(x, y) != piecetype.none) return moveresult.invalidmove;
you want cell button data , use i,j coordinates call getelement().
note: couple of comments on table class. default constructor doesn't make sense if know initial size of table. if case, make columns, rows , wincells final cannot modified during game. also, check coordinates provided in getelement() within array bounds:
public piecetype getelement(int i, int j) { if ((i < 0) || (i >= rows) || (j < 0) || (j >= columns)) { return null; } return table[i][j]; }
Comments
Post a Comment