I encountered the legendary StackOverflow error at lines 25 (random number) and line 29 (where fillGrid() recursively calls itself). I wish to know why this would happen as I have already provided the random number be incremented by one in case it does not fit legally, and if no number is possible then restart everything. I do not wish to get a Sudoku generator algorithm, as I could have googled that, I wish to get an answer as to why this is wrong.Adding a counter shows the program ran 5923 times before Stack overflowing.
import java.util.Random;
class Sudoku{
private Random random = new Random();
private int grid[][] = new int[9][9];
private int rndm, rowLB, rowUB, columnLB, columnUB;
private int count=0;
private void initialise(){
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
grid[i][j]=0;
}
}
}
private void fillGrid(){
initialise();
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
rndm = random.nextInt(9);
insert(rndm, i, j);
if (count==10){
initialise();
fillGrid();
}
}
}
}
private void insert(int number, int row, int column){
if(check(number, row, column)){
grid[row][column]=number;
}else if (count<=9){
count++;
insert((++number)%9, row, column);
}else{
return;
}
}
private boolean check(int number, int row, int column){
for (int i=0; i<9; i++) {
if (grid[i][column] == number || grid[row][i] == number) {
return false;
}
}
findBox(row, column);
for (int i=rowLB; i<rowUB; i++) {
for (int j=columnLB; j<columnUB; j++) {
if (grid[i][j]==number && !(i==row && j==column)){
return false;
}
}
}
return true;
}
private void findBox(int row, int column){
if (0<=row && row<=2){
rowLB=0; rowUB=2;
}else if (3<=row && row<=5){
rowLB=3; rowUB=5;
}else{
rowLB=6; rowUB=8;
}
if (0<=column && column<=2){
columnLB=0; columnUB=2;
}else if (3<=column && column<=5){
columnLB=3; columnUB=5;
}else{
columnLB=6; columnUB=8;
}
}
public static void main(String args[]){
Sudoku ob = new Sudoku();
ob.fillGrid();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(ob.grid[i][j]);
}
System.out.println();
}
}
}