0

I want to write a program that reads a matrix of positive int with the format txt (the matrix can be of any size). (I read the matrix from the console). The program looks for a location in the matrix such that if a knight is positioned at that location, all possible moves will land the knight on elements which have the same value and it must have at least 2 options. The program prints the result. for example, the black places are where the knight can move to.

This is the code I wrote. the problem is that i'm getting: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at Knights.main(Knights.java:23)", I know it has a problem with the first row (there is no backwards value in the start of the matrix) but I don't know how can I fix it.

 public static void main (String[] args)  {
   String size = StdIn.readLine();
   int counter = 0;
   int matrixSize = Integer.parseInt(size);
   int [][] matrix = new int [matrixSize+1][matrixSize+1];
   for (int i=0; i <= matrixSize-1; i++) {
      for (int j=0; j <= matrixSize-1; j++) {
          if ((matrix[i][j]) > 0)
            matrix[i][j] = StdIn.readInt();
      }
   }
   for (int k=0; k <= matrixSize-2; k++) {
      for (int l=0; l <= matrixSize-2; l++) {
        if (matrix[k-1][l+2] == matrix[k+1][l+2]) {
          counter +=1;
          StdOut.println(counter); }
        else if (matrix[k-1][l+2] == matrix[k+1][l-2]) {
          counter +=1;
          StdOut.println(counter); }
          if (counter>=2)
            StdOut.println("location "+ matrix[k][l] + "is surrounded by the number " +matrix[k+1][l-2]); 
        }
      }
    if (counter < 2)  
      StdOut.println("no surrender by any number");
    }
  }
Loren
  • 95
  • 10

1 Answers1

0

I would add an extra test here to check if k-1 is greater than 0.

As && is a short-circuit operator, the second expression is not tested if the first is false and can not throw an exception.


Solution

if (k - 1 > 0 && matrix[k - 1][l + 2] == matrix[k + 1][l + 2]) {
    counter += 1;
    StdOut.println(counter);
} else if (k - 1 > 0 && matrix[k - 1][l + 2] == matrix[k + 1][l - 2]) {
    counter += 1;
    StdOut.println(counter);
}
Community
  • 1
  • 1
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • I checked if it's greater than 0 here: for (int j=0; j <= matrixSize-1; j++) { if ((matrix[i][j]) > 0) matrix[i][j] = StdIn.readInt(); – Loren Nov 21 '15 at 15:34
  • But here I was talking about `k` in your second for loop. There is no check. + You are mistaking what's is inside the index with the index itself. – Yassin Hajaj Nov 21 '15 at 15:38
  • Thank you. Now I don't have a problem with the index-out-of-bounds but I do have a problem with the print line (output) in the end. The output gives the wrong values :/ – Loren Nov 21 '15 at 16:15