Java - 循环遍历二维数组以查找某个值的索引无法工作

4

我知道这段代码中有错误,但是我找不出来。player1.getId();返回的值是1,这点你要知道。我想打印出数组中值为1的元素的索引。在代码结尾处,我期望currentX为0,currentY为0,但它们都是9。希望能得到帮助。

int[][] grid = {
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
    {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}
};

int currentX = 0;
int currentY = 0;

grid[0][0] = player1.getId();

grid[0][9] = 2;

for (int i = 0; i < grid.length; i++) {
    for (int j = 0; j < grid[0].length; j++) {
        if (grid[i][j] == player1.getId());
        {
            currentX = i;
            currentY = j;
        }
        System.out.print(grid[i][j]);
    }

}
System.out.println();
System.out.println("Player1 is currently in row " + currentX + " and column " + currentY);

你确定你想在内部for循环中使用grid[0].length吗?看起来你是想要grid[i].length。 - hubson bropa
2个回答

6

if (grid[i][j] == player1.getId()); 的末尾移除分号(;)。

考虑一下 Java 中的 if 语句如何工作

Java 中的 if 语句会在其表达式为 true 时执行其块代码。分号会结束 Java 的语句。如果你在 if 语句后面放置一个空分号,它将被视为一个空语句。因此,在执行带有分号结尾的 if 语句时,if 语句什么也不做。Java 编译器会将您的代码编译成类似以下方式。

if (grid[i][j] == player1.getId()){
    //nothing here
}

{
    currentX = i;
    currentY = j;
}

看看其他类型语句在结尾加上分号会发生什么。

  • while loop

        while (expression);
        {
            //something goes here 
        }
    

当初始化 while 循环时,条件可以是 truefalse。如果条件是 true,它会创建一个无限循环,之后的代码不会执行。如果条件是 false,则它会执行一次 while 循环中期望执行的内容。

  • switch (integer);catch (Exception e);

编译失败并抛出异常 { expected


1
我只想补充一点,您可以通过将开括号放在同一行来防止此类错误发生。 - Cinnam
非常感谢您。我对这个疏忽感到困窘。 - Michael Arnold
训练自己在编程中先放置开括号,这样就不会出现这个错误了。当代码变得复杂时,很难识别这种错误。 - Channa Jayamuni

1
这里的条件是true(如果player1.getId() == 1):

if(grid[i][j] == player1.getId());

但是代码存在逻辑错误:一组运算符在此处——空操作符;,它将被执行...

currentXcurrentY始终等于数组的长度。

currentX = grid.length;
currentY = grid[0].length;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接