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

时间:2015-09-29 15:39:56

标签: 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);

2 个答案:

答案 0 :(得分:7)

删除;

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

考虑如何运作if java语句

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

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

{
    currentX = i;
    currentY = j;
}

看看当其他类型的声明最后有半冒号时会发生什么。

  • while循环

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

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

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

无法编译并获得异常{ expected

答案 1 :(得分:1)

此处的条件为true(如果player1.getId() == 1):

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

但是代码包含一个逻辑错误:这里有一组操作符 - 空操作符 ;并且它将被执行...

currentXcurrentY总是等于数组的长度。

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