[英]Java Sudoku - Not Changing Fields In 2D Array
我一直遇到一個問題。 我在Java方面相對較新,並且正在嘗試簡化一些比以前復雜的事情。 這是我自己的個人File輸入和main方法與其他方法的某些替代源的結合。 我對遞歸仍然不滿意。 由於某種原因,更改2D陣列“板”中的值的分配命令正常運行,但沒有更改值。 至少在結構上,一切看起來對我而言都是潔凈的,但是就像我說的那樣,我是新的。
另外,我正在尋找帶有完成程序的終端上的文本輸出,拋出異常似乎只是對終端的一種厭倦。 有什么建議么?
import java.util.Scanner;
import java.io.File;
public class Sudoku2{
static int board[][] = new int[10][10] ;
static int backtrack = 0;
public static void main(String[] args) throws Exception {
Sudoku2 myPuzzle = new Sudoku2();
// myPuzzle.readboard();
myPuzzle.readData("./board/input.txt");
myPuzzle.solve(0, 0);
printboard();
}
protected static void printboard(){
System.out.println("Here's your puzzle: ");
for(int r = 0; r < 9; r++){
for(int c = 0; c < 9; c++){
System.out.print(board[r][c]+" ");
}
System.out.println("");
}
}
public void readData(String filename) {
File inputFile = new File(filename);
try {
Scanner keyboard = new Scanner(inputFile);
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
board[row][col] = keyboard.nextInt();
}
}
keyboard.close();
}catch(Exception e){
System.out.print("Problem in readFile" + e);
e.printStackTrace();
}
}
//check if valid in row
protected static boolean validInRow(int row, int value)
{
for( int col = 0; col < 9; col++ )
if( board[row][col] == value )
return false ;
return true ;
}
//check if valid in column
protected static boolean validInCol(int col, int value)
{
for( int row = 0; row < 9; row++ )
if( board[row][col] == value )
return false ;
return true ;
}
//check if valid in 3*3
protected static boolean validInBlock(int row, int col, int value)
{
row = (row / 3) * 3 ;
col = (col / 3) * 3 ;
for( int r = 0; r < 3; r++ )
for( int c = 0; c < 3; c++ )
if( board[row+r][col+c] == value )
return false ;
return true ;
}
//call other methods
public void solve(int row, int col) throws Exception
{
if(row > 8)
{
printboard();
throw new Exception("Solution found") ;
}
else
{
while(board[row][col] != 0)
{
if( ++col > 8 )
{
col = 0 ;
row++ ;
if( row > 8 )
printboard();
throw new Exception( "Solution found" ) ;
}
}
for(int value = 1; value < 10; value++)
{
if(validInRow(row,value) && validInCol(col,value) && validInBlock(row,col,value))
{
board[row][col] = value;
//new PrintEvent(board);
if( col < 8 )
solve(row, col + 1);
else
solve(row + 1, 0);
backtrack++;
}
}
board[row][col] = 0;
}
}
}
Tenfour04的評論是正確的。 您的一個if語句中缺少一個括號。 在您的solve
方法中,以下代碼:
if ( row > 8 )
printboard();
throw new Exception( "Solution found" ) ;
應該更改為:
if ( row > 8 ) {
printboard();
throw new Exception( "Solution found" ) ;
}
另外,正如您自己提到的,您正在濫用Exception概念。 應該將異常用於處理真正異常的錯誤情況,而不僅僅是將某些內容打印到終端上。
您可以簡單地使用在printboard
方法中使用的System.out.println
方法,如下所示:
if ( row > 8 ) {
printboard();
System.out.println( "Solution found" ) ;
return;
}
在這里,我還添加了return
關鍵字,以使程序在找到solve
方案時退出solve
方法。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.