Java - Looping 2d Array to find index of a value not working

后端 未结 2 917
孤街浪徒
孤街浪徒 2021-01-19 23:34

I know I\'m making an error somewhere in this code, but I can\'t figure it out. The player1.getId(); returns a value of 1 just so you are aware. I\'m trying to print the i

2条回答
  •  自闭症患者
    2021-01-19 23:57

    Remove the semicolon(;) at the end of if (grid[i][j] == player1.getId());

    Consider how works if statement of java

    The if statement of java executes it's block code if the expression of if statement is true. Semi colon ends a statement of java. If you put empty semi colon after if statement it counts as an empty statement. So, if statement does nothing when executing if statement which having semi colon at the end. Java compiler compiles your code similarly as follows.

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

    See what happens when other kind statement had semi colon at the end.

    • while loop

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

    The condition can be true or false when initializing while loop. If the condition is true it makes an infinite loop. Nothing will execute after the line. If expression is false, it executes once the expected content of while loop.

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

    It fails to compile and getting an exception { expected

提交回复
热议问题