Unexpected ArrayOutOfBoundsError
In a program I am writing for homework, one method yields an unexpected error:
(The variable n has been declared 9 earlier in the program)
Code Java:
private boolean[] getAllowedValues(int row, int col) {
boolean[] valNums = new boolean[n];
// Set the initial value of all squares to true
for (int i = 0; i < n; i++)
valNums[i] = true;
// Check row
for (int i = 0; i < n; i++) {
if (board[row][i] != LOCATION_EMPTY)
valNums[board[row][i]] = false;
}
// Check column
for (int i = 0; i < n; i++) {
if (board[i][col] != LOCATION_EMPTY)
valNums[board[i][col]] = false;
}
// Check the nine sub-grids
int rl = (row / 3) * 3;
int rh = (row / 3) * 3 + 3;
int cl = (col / 3) * 3;
int ch = (col / 3) * 3 + 3;
for (int r = rl; r < rh; r++) {
for (int c = cl; c < ch; c++) {
if (board[r][c] != LOCATION_EMPTY)
valNums[board[r][c]] = false;
}
}
System.out.println(valNums);
return valNums;
}
This is the error I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at Sudoku.SudokuPuzzle.getAllowedValues(SudokuPuzzle. java:232)
at Sudoku.SudokuPuzzle.main(SudokuPuzzle.java:278)
This method is called in the main method as a part of the Sudoku constructor as part of a switch:
Code Java:
case 'H':
int row = 0;
int col = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter a row for allowed values: ");
row = in.nextInt();
System.out.print("Enter a column for allowed values: ");
col = in.nextInt();
Sudoku.getAllowedValues(row, col);
Thanks!
Re: Unexpected ArrayOutOfBoundsError
There is some missing information here that makes it hard to diagnose. On which line in particular is the exception thrown (the line in the stack trace and the code you posted do not line up)? You reference an array named 'board'...what is this, and where is this defined? What values are you inputting from the command line?
Re: Unexpected ArrayOutOfBoundsError
I'm surprised it's not saying
valNums[board[i][col]] = false;
This might be the problem.
Re: Unexpected ArrayOutOfBoundsError
I think I may have a theory as to what may be going wrong.
Is it possible that you're telling it to do something with index 9, when there'd only be 8 values or something like that?
Re: Unexpected ArrayOutOfBoundsError
Code java:
private boolean[] getAllowedValues(int row, int col) {
boolean[] valNums = new boolean[n];
// Set the initial value of all squares to true
for (int i = 0; i < n; i++)
valNums[i] = true;
Yeah the loop asks for an array index that isn't there. Lets say n = 3. i goes from 0-3 which is 4 indexes. Java spits out error when i = 3 and valNums[] has no index for it.