0

我正在扫描一个带有几个分隔符的数独板的文本文件。这就是示例输入的样子。

1 - - | 4 5 6 | - - -  
5 7 - | 1 3 b | 6 2 4  
4 9 6 | 8 7 2 | 1 5 3  
======+=======+======  
9 - - | - - - | 4 6 -  
6 4 1 | 2 9 7 | 8 3 -  
3 8 7 | 5 6 4 | 2 9 -  
======+=======+======     
7 - - | - - - | 5 4 8   
8 r 4 | 9 1 5 | 3 7 2   
2 3 5 | 7 4 $ | 9 1 6  

哪里有“|” 作为边界和 =====+====+==== 作为分隔符。我做了这个代码来忽略 | 和 ====+===+=== 但它跳过了那部分代码并将它们声明为无效字符并在那里添加 0

public static int [][] createBoard(Scanner input){

    int[][] nSudokuBoard = new int[9][9];

  for (rows = 0; rows < 9; rows++){

        for (columns = 0; columns < 9; columns++){

            if(input.hasNext()){

                if(input.hasNextInt()){
                    int number = input.nextInt();
                    nSudokuBoard[rows][columns] = number;
               }//end if int

                else if(input.hasNext("-")){
                    input.next();
                    nSudokuBoard[rows][columns] = 0;
                    System.out.print("Hyphen Found \n");
                    }//end if hyphen

                else if(input.hasNext("|")){
                    System.out.print("border found \n");
                    input.next();

                }// end if border
                else if(input.hasNext("======+=======+======")){
                    System.out.print("equal row found \n");
                    input.next();
                }// end if equal row

               else {
                   System.out.print("Invalid character detected at... \n Row: " + rows +" Column: " + columns +"\n");
                   System.out.print("Invalid character(s) replaced with a '0'. \n" );
                   input.next();
               }//end else

            }//end reading file
       }//end column for loop
    }//end row for looop
 return  nSudokuBoard;
}//end of createBoard

我和导师讨论过,但我不记得他关于如何解决这个问题的建议。

4

2 回答 2

1

String 参数 tohasNext被视为正则表达式。您需要转义特殊字符:

else if(input.hasNext("\\|")){

else if(input.hasNext("======\\+=======\\+======")){

http://ideone.com/43j7R

于 2012-02-19T04:35:47.700 回答
0

即使您使用边框或分隔线,您的循环也会增加行和列计数器。因此,即使您解决了其他问题(如上一个答案中所述),您仍将在阅读所有输入之前完成填充矩阵。您需要修改代码以仅在您使用整数或破折号后有条件地推进行和列计数器。这意味着删除for循环,将第一个循环更改if(input.hasNext())为 a while,并rows++columns++您使用整数或破折号并为nSudokuBoard[rows][columns]. 您还需要逻辑来确定何时增加rows以及何时设置columns0.

此外,从风格上讲,您应该重命名rowsrow和。columnscolumn

于 2012-02-19T04:52:07.040 回答