简体   繁体   中英

Java Sudoku Solver Output

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.)

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.

You have at least 4 problems that I see right away:

  1. You don't print a newline at the end of your outer ( row ) loop
  2. The if(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 column
  3. column == temp-1 etc. will only work for the 2x2 case, it should be column > 0 && column % temp == 0
  4. Don't ever ever modify a for loop variable inside the loop, that will confuse everything and usually cause ArrayIndexOutOfBoundsException , as happens here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM