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に変更し、整数またはダッシュを消費して の値を設定している場所にandwhileを追加することを意味します。また、インクリメントするタイミングと に戻すタイミングを決定するロジックも必要です。rows++columns++nSudokuBoard[rows][columns]rowscolumns0

また、スタイル的に言えば、名前rowsrowおよびcolumnsに変更する必要がありますcolumn

于 2012-02-19T04:52:07.040 に答える