Reputation: 1794
I'm having some problems with my Sudoku Solver that I need to make, what I am supposed to do is to create a program which checks to see if the inputted Sudoku puzzle is correct or not. I have the code which checks to see if each row, column, and "minibox" working. My only problem now is to print out the puzzle. This is what I have so far:
public String printGrid(int size, int[][] puzzle){
double temp = Math.sqrt(size);
for(int row = 0; row < size; row++){
for(int column = 0; column < size; column++){
System.out.print(puzzle[row][column]);
if(column == temp - 1) {
System.out.print("|");
}
if(row == temp - 1){
for(int i = 0; i < size; i++){
System.out.print("-\t");
}
}
if(column == size - 1) {
column = 0;
row++;
}
}
}
return "Correct!";
}
As an example size will be 4 and the inputted sudoku will be:
1 2 3 4
4 3 2 1
3 4 1 2
2 1 4 3
My output is to look like this:
1 2 | 3 4
4 3 | 2 1
----+----
3 4 | 1 2
2 1 | 4 3
My current code however gives an ArrayOutOfBounds error and outputs this:
- 2- - - - 1- - - - 4|121|43
I'm completely lost in how to write this method to output, can anyone shed some light on this for me? (Also ignore the fact that all sudokus return "Correct!" I should be able to figure that out myself.)
Upvotes: 0
Views: 752
Reputation: 213193
if(column == size - 1) {
column = 0;
row++;
}
Using the above if-statement
, you are not letting the inner loop to get terminated
, because everytime the column
value reaches the dead-end, you are resetting
it to 0
, and hence the terminating condition of inner loop (column < size)
will always be true, and also you are increasing the row
value continuously, which will gradually result ArrayIndexOutOfBounds
.
Just remove that if
condition. It is not needed.
Upvotes: 3
Reputation: 32323
You have at least 4 problems that I see right away:
row
) loopif(row == temp - 1)
loop should be in the outer loop only (you want to do it on it's own row, not each time in the columncolumn == temp-1
etc. will only work for the 2x2 case, it should be column > 0 && column % temp == 0
for
loop variable inside the loop, that will confuse everything and usually cause ArrayIndexOutOfBoundsException
, as happens here.Upvotes: 1