2d interger数组的元素没有得到比较。不要试图比较整个阵列

时间:2016-10-12 17:03:19

标签: java arrays for-loop multidimensional-array

我只是在梳理我的java技能,因为我编码已经有一段时间了。我查看了很多关于我的问题的帖子,发现我似乎正在比较所有内容,据我所知。我正在比较两个2d数组元素,如果匹配我替换元素上的字符,但是当试图比较它们时似乎只是超出界限。没有看到越界错误(第48行)。

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

2 个答案:

答案 0 :(得分:0)

你的播放器(i)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进行比较。 因此,它试图将字符的整数值与要比较的变量值进行比较。

答案 1 :(得分: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,它不是数组的有效索引。您应该将该输入作为整数,然后在数组中设置该值(没有循环来找到正确的点)。