0

So my code should allow you to insert 81 digits in a string "893273872328..." and categorizes them into a matrix in the order typed. My code:

Scanner scan = new Scanner(System.in);
    String rawIn = new String(scan.nextLine());
    int[][] matIn = new int[8][8];
    for(int row = 0; row <=8; row++){
        for(int col = 0; col <=8; col++){
            matIn[row][col] = Integer.parseInt(rawIn.substring(((row+1)*(col+1)-1),(row+1)*(col+1)));
        }
    }

But when i run this and enter 81 digits is gives me this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8

Any explaination as to why its doing this, is my algorithm flawed?

  • Your loop will go from 0 to 8, inclusive. But your arrays only have 8 spaces, meaning the max index is 7. So when you try to set `matIn[row]` it's using `matIn[8]` which is out of bounds. – whitfin Apr 16 '18 at 00:48
  • The last index in arrays is at `length - 1` and the first at `0`. Your rows and columns have a length of `8` so the last element is at index `7`. You need to adjust your `for` loops to only iterate to `7` maximally, so `row < 8` and `col < 8`. The exception itself is obvious, you tried to access index `8` which is out of bounds. – Zabuzard Apr 16 '18 at 00:49

0 Answers0