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

I know that I am making a mistake somewhere in this code, but I cannot figure it out. Player1.getId (); returns a value of 1 so you know. I am trying to print the index of an array where the value is 1. At the end of the code, I expected currentX to be 0 and currentY to be 0, but they are both equal 9. Any help would be great.

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); 
+5
source share
2 answers

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

Let's see how if java instruction works.

The if java executes the block code if the if is true . A halftone column completes the java statement. If you put an empty colon after the if statement, it is considered an empty statement. Thus, the if does nothing when executing an if , which ultimately has a colon. The Java compiler compiles your code in a similar fashion as follows.

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

See what happens if at the end of another expression with the expression "half-density".

  • while loop

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

When a while initialized, the condition can be true or false . If the condition is true , it creates an infinite loop. After the line, nothing will be executed. If the expression is false , it is executed after the expected contents of the while .

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

Unable to compile and get { expected

+7
source

The condition is true here (if player1.getId() == 1 ):

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

But the code contains a logical error: there is a group of operators - an empty operator ; and it will be executed ...

currentX and currentY will always be equal to the length of the array.

 currentX = grid.length; currentY = grid[0].length; 
+1
source

Source: https://habr.com/ru/post/1232546/


All Articles