我是编程的初学者。在Java中我的暴力数独求解器程序中,我继续在第34行中为索引0获取一个超出绑定异常的数组!怎么能超出界限?请检查代码并告诉我您是否找到了缺陷的位置。 感谢
import java.io.*;
class brute_sudoku
{
public static void main(String args[])throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements of the sudoku using 0 for blanks");
int m[][] = new int[9][9];
for(int r = 0; r < 9; r ++)
{
System.out.println("Enter row " + (r + 1));
String row = in.readLine();
for(int c = 0; c < 9; c ++)
m[r][c]= row.charAt(c);
}
int blanks = 0;
for(int r = 0; r < 9; r ++)
for(int c = 0; c < 9; c++)
if(m[r][c] == 0)
blanks ++;
int n[] = new int[blanks];
blanks = 0;
for(int r = 0; r < 9; r ++)
for(int c = 0; c < 9; c++)
if(m[r][c] == 0)
{
n[blanks] = r*10 +c;
blanks ++;
}
int i = blanks;
while(true)
{
if(m[n[i]/10][n[i]%10] == 9)
{
m[n[i]/10][n[i]%10] = 1;
i --;
continue;
}
else
{
m[n[i]/10][n[i]%10] ++;
boolean solved = true;
int count = 0;
for(int r = 0; r < 9; r ++)
{
count = 0;
for(int c = 0; c < 9; c ++)
count = count + m[r][c];
if(count != 45)
solved = false;
}
for(int c = 0; c < 9; c ++)
{
count = 0;
for(int r = 0; r < 9; r ++)
count = count + m[r][c];
if(count != 45)
solved = false;
}
for(int r = 2; r < 9; r = r + 3)
for(int c = 2; c < 9; c = c + 3)
{
count = 0;
for(int r1 = r -2; r1 <=r; r1 ++)
for(int c1 = c -2; c1 <= c; c1 ++)
count = count = m[r1][c1];
if(count != 45)
solved = false;
}
if(solved)
break;
else
{
i = blanks;
continue;
}
}
}
System.out.println("Solved sudoku is:");
for(int r =0; r < 9; r ++)
{
for(int c = 0; c < 9; c ++)
System.out.print(m[r][c]);
System.out.println();
}
}
}
答案 0 :(得分:0)
第34行if(m[n[i]/10][n[i]%10] == 9)
以上的行肯定会导致数组超出界限例外,因为:
语句n[i] % 10
,它可以返回0到9之间的任何内容。如果它返回9,那就是灾难!