Java - 循环2d数组以查找值不起作用的索引

Mic*_*old 5 java

我知道我在这段代码的某个地方犯了一个错误,但我无法弄明白.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);
Run Code Online (Sandbox Code Playgroud)

Cha*_*uni 7

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

考虑一下ifjava的工作原理

ifJava的声明如果表达式执行它的代码块if声明true.半冒号结束了java的声明.如果在if语句之后放入空的半冒号,则将其视为空语句.因此,if当执行if末尾有半冒号的语句时,语句不执行任何操作.Java编译器类似地编译您的代码,如下所示.

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

{
    currentX = i;
    currentY = j;
}
Run Code Online (Sandbox Code Playgroud)

看看当其他类型的声明最后有半结肠时会发生什么.

条件可以是truefalse在初始化while循环时.如果条件是true它会产生无限循环.该行之后什么都不会执行.如果表达式是false,它将执行一次预期的while循环内容.

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

它无法编译并获得异常 { expected