gpt4 book ai didi

Java 数独解算器抛出除以零 ArithmeticException

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:55 28 4
gpt4 key购买 nike

我正在用 Java 做这个数独求解器,由于某种原因,我的代码中有一个我无法修复的错误。我的代码有一个 guess 函数,它在检查每个框中的 1-9 数字的同时检查数字是否已经写入。

错误在行中:

 else if (board[r + (i % 3)][c + (i / 3)] == num)

由于某种原因我无法理解为什么会出现 ArithmeticException(除以 0)。希望你能帮忙

我的代码:

public class SudokuSolver
{
final int size = 9;
private int box_size;

private int[][] board;

// Create an empty board
public SudokuSolver()
{
board = new int[size][size];
this.box_size = size / 3;

}

// initialize a given board
public SudokuSolver(int[][] board)
{
this.board = board;
}

public void setCell(int num, int row, int col)
{
board[row][col] = num;
}

public int getCell(int row, int col)
{
return board[row][col];
}

private boolean check(int num, int row, int col)
{
int r = (row / 3) * 3;
int c = (col / 3) * 3;

for (int i = 0; i < size; i++)
{
if (board[row][i] == num)
return false;

else if (board[i][col] == num)
return false;

else if (board[r + (i % box_size)][c + (i / box_size)] == num)
return false;
}
return true;
}

public boolean guess(int row, int col)
{
int nextCol = (col + 1) % size;
int nextRow = (nextCol == 0) ? row + 1 : row;

try
{
if (board[row][col] != 0)
return guess(nextRow, nextCol);
}
catch (ArrayIndexOutOfBoundsException e)
{
return true;
}

for (int i = 1; i <= size; i++)
{
if (check(i, row, col))
{
board[row][col] = i;
if (guess(nextRow, nextCol))
{
return true;
}
}
}
board[row][col] = 0;
return false;
}

public void printBoard()
{
for (int row = 0; row < size; row++)
{
for (int col = 0; col < size; col++)
{
System.out.print(board[row][col] + " ");
}
System.out.println();
}

}



public static void main(String[] args)
{

int[][] board = { { 0, 6, 0, 1, 0, 4, 0, 5, 0 },
{ 0, 0, 8, 3, 0, 5, 6, 0, 0 }, { 2, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 8, 0, 0, 4, 0, 7, 0, 0, 6 }, { 0, 0, 6, 0, 0, 0, 3, 0, 0 },
{ 7, 0, 0, 9, 0, 1, 0, 0, 4 }, { 5, 0, 0, 0, 0, 0, 0, 0, 2 },
{ 0, 0, 7, 2, 0, 6, 9, 0, 0 }, { 0, 4, 0, 5, 0, 8, 0, 7, 0 } };

SudokuSolver ss = new SudokuSolver(board);
ss.printBoard();
System.out.println();
System.out.println();
if(ss.guess(0, 0))
ss.printBoard();


}

最佳答案

在遇到错误的点之前打印 box_size 将显示它实际上是 0。您永远不会在此构造函数中初始化它,因此它保留其默认值 0:

public SudokuSolver(int[][] board) {
this.board = board;
}

您可能打算包含像 this.box_size = board.length/3 这样的行。


P.S. 导致错误的真实行是

else if (board[r + (i % box_size)][c + (i / box_size)] == num)

您可能不应该用 box_size 代替您在问题中的预期值。

关于Java 数独解算器抛出除以零 ArithmeticException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13498252/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com