Checking array won't work in function. (Java)

Viewed 35

I have the following code to check for 2d array m, to see if any adjacent values to number 1, are equal to 6. However left is always true, and down is always false, no matter how I change the code. feel free to change any code or do whatever you want, it does not matter in this case.

int[][] m = {{6, 0, 0, 0, 0},
             {0, 0, 6, 0, 6},
             {0, 6, 5, 0, 6},
             {6, 1, 6, 6, 0},
             {0, 0, 0, 0, 0}};
algo(m);
public static void algo(int[][] m) {
  //checking array for finish line and player
  int rows = m.length;
  int collums = m[1].length;
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < collums; j++) {
      if (m[i][j] == 1) {
        // Found the correct i,j - print them or return them or whatever
        int finishX = j;
        int finishY = i;
        System.out.println(finishX + "," + finishY);
      }
      if (m[i][j] == 5) {
        // Found the correct i,j - print them or return them or whatever
        int startX = j;
        int startY = i;
        System.out.println(startX + "," + startY);
        System.out.println("AdjacentCheck: " + checkAdjacent(m, startX, startY));
      }
    }
  }
}
public static String checkAdjacent(int[][] m, int x, int y) {

  String cache = "";
  if (m[x + 1][y] == 6) {
    cache += "Right";
    System.out.println("Right:" + m[x + 1][y] + "coords" + (x + 1) + "," + y);
  }
  if (m[x - 1][y] == 6) {
    cache += "Left";
    System.out.print("x= " + x);
    System.out.println("Left:" + m[x - 1][y] + "coords" + (x - 1) + "," + y);
  }
  if (m[x][y + 1] == 6) {
    cache += "Down";
    System.out.println("Down:" + m[x][y + 1] + "coords" + x + "," + (y + 1));
  }
  if (m[x][y - 1] == 6) {
    cache += "Up";
    System.out.println("up:" + m[x][y - 1] + "coords" + x + "," + (y - 1));
  } {
    if (cache.equals("")) {
      return "None";
    }
    return cache;
  }
}
1 Answers

there typo in this line

if (m[x - 2][y] == 6) {

it should be

if (m[x - 1][y] == 6) {

please notice to check if x or way on the edge for example if x/y is 0 or 4

there another issue on that line

if (m[i][j] == 1) {
    // Found the correct i,j - print them or return them or whatever
    int finishX = j;
    int finishY = i;
    System.out.println(finishX + "," + finishY);
  }
  if (m[i][j] == 5) {
    // Found the correct i,j - print them or return them or whatever
    int startX = j;
    int startY = i;
    System.out.println(startX + "," + startY);
    System.out.println("AdjacentCheck: " + checkAdjacent(m, startX, startY));
  }

why you check for 5 in if and in the other if statment you check for 1

and have a nice day :)

Related