[英]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: 例如,大小将为4,而输入的数独将为:
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: 但是我当前的代码给出了ArrayOutOfBounds错误并输出:
- 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.) (也忽略所有sudokus都返回“正确!”的事实,我应该能够弄清楚这一点。)
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
. 使用上面的if-statement
,您不会让内部循环terminated
,因为每次column
值到达死角时,您都resetting
其resetting
为0
,因此内部循环的终止条件(column < size)
将始终为true,并且您还在连续增加row
值,这将逐渐导致ArrayIndexOutOfBounds
。
Just remove that if
condition. 只是删除if
条件。 It is not needed. 不需要。
You have at least 4 problems that I see right away: 您立即至少遇到了4个问题:
row
) loop 您不在外部( row
)循环的末尾打印换行符 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 if(row == temp - 1)
循环应仅在外部循环中(您要在它自己的行上进行,而不是每次在列中进行一次 column == temp-1
etc. will only work for the 2x2 case, it should be column > 0 && column % temp == 0
column == temp-1
等。仅适用于2x2情况,它应为column > 0 && column % temp == 0
for
loop variable inside the loop, that will confuse everything and usually cause ArrayIndexOutOfBoundsException
, as happens here. 永远不要for
循环内部修改for
循环变量,这会混淆所有内容,并且通常会导致ArrayIndexOutOfBoundsException
,就像这里发生的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.