2016-10-12 46 views
0

我只是刷牙我的Java技能,因爲它已經有一段時間,因爲我已經編碼。我已經看了很多我的問題的帖子,發現我似乎正在比較一切正確的,據我所知。我將兩個2d數組元素相互比較,如果匹配,則替換元素處的字符,但是在嘗試比較它們時,似乎只是出界了。沒有看到超出界限的錯誤(第48行)。2d整數數組的元素沒有得到比較。沒有試圖比較整個陣列

char[][] board = new char[3][3]; 
 
char[][] player1 = new char[1][1]; 
 
char[][] player2 = new char[1][1]; 
 
int playerRow = 0; 
 
int playerCol = 0; 
 
Scanner kbd = new Scanner(System.in); 
 

 
System.out.println("Lets play a simple game of tic-tac-toe"); 
 
     System.out.println("Player 1 (X's) : Please enter a row number and column number "); 
 
     System.out.println(" in order to plot the cordinates of your desired move"); 
 
     playerRow = kbd.next().charAt(0); 
 
     playerCol = kbd.next().charAt(0); 
 
     for(int row = 0; row < board.length; row++) 
 
     { 
 
      for(int col = 0; col < board[row].length;col++) 
 
      { 
 
       if (board[row][col] == player1[playerRow][playerCol]) 
 
       { 
 
        board[row][col] = 'X'; 
 
        System.out.print(board[row][col]+" "); 
 
       } 
 
       else 
 
       { 
 
        board[row][col]= '-'; 
 
        System.out.print(board[row][col]+" "); 
 

 
       } 
 
      } 
 
      System.out.println(); 
 
     }

+0

你正在比較'char'到'int'。這是一個有效的比較,但可能不會做你想做的。例如,「1」(char)與「1」(int)不同。 – resueman

+0

哎呦。哦,我看了45分鐘。 –

+0

我改變了,但是它不斷給我一個數組索引超出界限的錯誤,我做了播放器數組char陣列。這個可以嗎? @resueman –

回答

0

你的代碼看起來像是你採取了錯誤的方法來解決這個問題。除非我誤解你的目的,否則我認爲player1player2是必要的。一切都應該存儲在board。下面是什麼,可能看起來像一個例子:

//initialize variables 
char[][] board = new char[3][3]; 
int playerRow = 0; 
int playerCol = 0; 

//clear the board 
for(int row = 0; row < board.length; row++){ 
    for (int col = 0; col < board[row].length; col++){ 
     board[row][col] = '-'; 
    } 
} 

Scanner kbd = new Scanner(System.in); 

System.out.println("Lets play a simple game of tic-tac-toe"); 
System.out.println("Player 1 (X's) : Please enter a row number and column number "); 
System.out.println(" in order to plot the cordinates of your desired move"); 

//get player's row and column 
playerRow = kbd.nextInt(); 
playerCol = kbd.nextInt(); 

//Change the chosen spot to be the player's character. 
board[playerRow][playerCol] = 'X'; 

//Display the board 
for(int row = 0; row < board.length; row++){ 
    for(int col = 0; col < board[row].length;col++){ 
     System.out.print(board[row][col] + " "); 
    } 
    System.out.println(); 
} 

這是一招,它可以讓玩家選擇一個點,然後顯示板的一個例子。

你當前得到錯誤的原因是因爲你閱讀了字符'0',然後嘗試使用它作爲數組的索引。但'0'0不一樣;它實際上是代表字符0的Unicode值,該字符恰好具有值48,該值不是數組中的有效索引。你應該把這個輸入作爲一個整數,然後在數組中簡單地設置該值(沒有找到正確的點的循環)。

+0

謝謝大家尤其是resueman和@vergeA。我總是傾向於糾纏我的程序追逐堆疊在另一個上面的修補程序的兔子洞。我確實是在我需要的地方,但看不到它。感謝你們。很愛每個人。 –

0

播放機(ⅰ)2- d陣列涉及分配一個char 2-d陣列爲整數2-d陣列。

char [] [] player1 = new int [board.length] [board.length]; char [] [] player2 = new int [board.length] [board.length];

我不認爲這是一個可行的初始化。

同樣如上面的評論中提到的,你正在比較一個char和一個int。 因此,它試圖比較你的字符的整數值和被比較的變量值。

+0

很抱歉,這是代碼中的錯誤。該錯誤仍然存​​在。 –

+0

你的棋盤是一個3×3的二維數組,而玩家只有1 * 1,因此它會超出界限。 –

+0

是的,這對我來說非常有意義,這裏我的邏輯錯誤是什麼? –