2012-02-19 56 views
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 

我带家教,但我不谈论它了不记得他如何解决这个问题的建议。

+0

你是怎样编辑James的? – 2012-02-19 04:23:16

+0

您可以点击“1分钟前编辑过”来查看编辑。在这种情况下,他只是将代码的最后一行的格式化。 – 2012-02-19 04:24:26

+0

哇。整洁的功能。谢谢欧内斯特。 – 2012-02-19 04:25:29

回答

0

你的循环递增,即使你是消费边界或分隔符的行和列计数器。因此,即使在解决其他问题之后(如前面的解答所述),在读完所有输入之前,您将完成填充矩阵。只有在使用整数或短划线后,才需要修改代码以有条件地前进行和列计数器。这意味着要删除for循环,将第一个if(input.hasNext())更改为while,并在您已使用整数或破折号并将值设置为nSudokuBoard[rows][columns]的地方添加rows++columns++。您还需要逻辑来确定何时增加rows以及何时将columns设置回0

此外,从文体上讲,您应该将rows重命名为rowcolumnscolumn

+0

我会尝试实施如何计算每行的列,但我无法弄清楚。但生病尝试你的建议,只有当我使用整数和破折号递增行和列 – 2012-02-19 05:27:34

+0

我想我正确实施了你的建议,但它运行到错误(ArrayIndexOutOfBounds) – 2012-02-19 05:40:53

+0

每当你使用一个int或破折号除了存储值,做到这一点:'列++; if(column == 9){column = 0;行++; }' – 2012-02-19 05:58:59

1

hasNext的字符串参数视为正则表达式。您需要将特殊字符转义:

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

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

http://ideone.com/43j7R

+0

哇。很酷的链接到ideone网站。感谢不好实施这个并跟进。 – 2012-02-19 05:26:33

+0

非常感谢!你的建议完美无缺。 – 2012-02-19 06:14:27