2012-06-05 5 views
-1

이유를 정확히 이해하지 못하는 오류가 나타납니다. 는 (N × N)의 여기 테이블 클래스를이다하여 ticTacToe 게임 ArrayIndexOutOfBounds TicTacToe 게임에서 예외가 발생했습니다.

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]; 
} 

그 제가 game.move (e.x, e.y)에 함수를 호출 한 후에 에러를주는 getElement() 메소드; 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()); 

어떤 아이디어를 얻을 곳

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(); 
     } 

이 무엇입니까? 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) 

여기하여 마우스 클릭 좌표하는 SelectionEvente

if(table.getElement(x, y) != PieceType.None) return MoveResult.InvalidMove; 
+0

/당신은 어떻게'getElement' 방법을 요구하고있다? – npinti

+0

스택 추적을 게시하십시오. 문제가 발생한 줄을 정확히 보여줍니다. 또한 기본 생성자를 사용하면 필드가 초기화되지 않으므로 문제가 발생할 수 있습니다. 기본값을 제공하거나 기본 생성자를 제공하지 않는 것이 좋습니다. – toniedzwiedz

답변

2

당신은 아마 Button 데이터로부터 Cell을 얻고 getElement()를 호출 할 i,j 좌표를 사용하고 싶습니다.

참고 : Table 클래스에 대한 몇 가지 의견이 있습니다. 기본 생성자는 이미 테이블의 초기 크기를 알고있는 경우 의미가 없습니다. 이 경우 columns, rowswincellsfinal을 게임 중에 수정할 수 없도록 설정하십시오. 또한, getElement()에서 제공하는 좌표가 배열 범위 내에 있는지 확인하십시오

public PieceType getElement(int i, int j) { 
    if ((i < 0) || (i >= rows) || 
     (j < 0) || (j >= columns)) { 
     return null; 
    } 

    return table[i][j]; 
} 
+0

정렬되었습니다. 감사합니다. –

0

e.xe.y를 호출하는 방법, 그리고 그리드입니다. Button 데이터에서 Cell을 가져온 다음 게임 이동에 사용해야합니다. 당신은 그런 당신의 widgetSelected 방법을 수정할 수 있습니다

Cell c = (Cell) button.getData(); 
// Then use i and j of the cell for the game move 
game.move(c.i, c.j); // or something similar 
+0

나는 당신의 방법을 시도하고 어쩌면 지금부터 나는 동일한 예외를 얻었지만 동일한 방법으로 2 번을 얻었습니다. –

+0

정렬되었습니다. 감사합니다. –

0
import java.util.Scanner; 

public class TicTacToe_Game { 

    public static void main(String[] args) { 
     Scanner Myinput = new Scanner(System.in); 
     char[][] board = new char[3][3]; 

     boolean Gameover; 
     Gameover = CalculateWinner(board); 
     while(!Gameover){ 

     displayBoard(board); 
     System.out.println("Enter row and column for player X"); 
     int rowX, columnX; 
     rowX=Myinput.nextInt(); 
     columnX= Myinput.nextInt(); 
     boolean successX = setMove(rowX , columnX ,board,'X'); 
     while(!successX){ 
      System.out.println("INVALID MOVE FOR PLAYER X"); 
      System.out.println("Re-Enter row and column for player X"); 
      rowX=Myinput.nextInt(); 
      columnX= Myinput.nextInt(); 
      successX = setMove(rowX , columnX ,board,'X'); 
     } 
     Gameover= CalculateWinner(board); 

     displayBoard(board); 
     System.out.println(); 
     System.out.println("Enter row and column for player O"); 
     int rowO, columnO; 
     rowO=Myinput.nextInt(); 
     columnO= Myinput.nextInt(); 
     boolean successO= setMove(rowO , columnO ,board,'O'); 
     while(!successO){ 
      System.out.println("invalid Move"); 
      System.out.println("Re-Enter row and column for player O"); 
      rowO=Myinput.nextInt(); 
      columnO= Myinput.nextInt(); 
      successO = setMove(rowO , columnO ,board,'0'); 
     } 
     Gameover=CalculateWinner(board); 
     } 
    } 
    public static boolean setMove(int row, int column,char[][] board,char player){ 
     if(board[row][column]== 'X' || board[row][column]== 'O'){ 
      return false; 
      } 
      else if (player =='X'){ 
      board[row][column] = 'X'; 
      return true; 
      } 
      else{ 
      board[row][column] = 'O'; 
    return true; 
      } 
    } 
    public static void displayBoard(char[][]board){ 
     System.out.println("-------------------"); 
     System.out.println("|"+board[0][0]+"|"+board[0][1]+"|"+board[0][2]+"|"); 
     System.out.println("-------------------"); 
     System.out.println("|"+board[1][0]+"|"+board[1][1]+"|"+board[1][2]+"|"); 
     System.out.println("-------------------"); 
     System.out.println("|"+board[2][0]+"|"+board[2][1]+"|"+board[2][2]+"|"); 
     System.out.println("-------------------"); 
    } 
    public static boolean CalculateWinner(char[][] board){ 
     boolean filled =false; 
     for(int column=0; column<=2; column++){ 
      for(int row =0; row<=2; row++){ 
       if (board[column][row]!='X'&& board[column][row]!='O'){ 
        filled = false; 

       } 
       else 
       { filled = true; 
      } 
     } 
    } 
     if (filled){ 
      return true; 
     }else { 
      return false; 
     } 
} 
} 
+0

OP에 코드를 설명해 주시겠습니까? –

관련 문제