2016-10-12 43 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

是的,这对我来说非常有意义,这里我的逻辑错误是什么? –