扫描程序/令牌错误java

时间:2015-10-23 19:04:15

标签: java string java.util.scanner token line-processing

我正在编写一个从文本文件中读取体育数据的程序。每一行都有字符串和整数混合在一起,我试图只阅读团队的分数。但是,即使行有整数,程序也会立即转到else语句而不打印分数。我有两个input2.nextLine()语句,因此它会跳过两个没有分数的标题行。我该如何解决这个问题?

以下是代码:

public static void numGamesHTWon(String fileName)throws FileNotFoundException{
    System.out.print("Number of games the home team won: ");
    File statsFile = new File(fileName);
    Scanner input2 = new Scanner(statsFile);


    input2.nextLine();
    input2.nextLine();

    while (input2.hasNextLine()) {
        String line = input2.nextLine();
        Scanner lineScan = new Scanner(line);
        if(lineScan.hasNextInt()){

            System.out.println(lineScan.nextInt());
            line = input2.nextLine();

        }else{
            line = input2.nextLine();



        }
    }
}

这是文本文件的顶部:

NCAA Women's Basketball
2011 - 2012
2007-11-11 Rice 63 @Winthrop 54 O1
2007-11-11 @S Dakota St 93 UC Riverside 90 O2
2007-11-11 @Texas 92 Missouri St 55
2007-11-11 Tennessee 76 Chattanooga 56
2007-11-11 Mississippi St 76 Centenary 57
2007-11-11 ETSU 75 Delaware St 72 O1 Preseason NIT

1 个答案:

答案 0 :(得分:0)

方法hasNextInt()尝试检查立即字符串是否为int? 。所以这个条件不起作用。

public static void numGamesHTWon(String fileName) throws FileNotFoundException {
        System.out.print("Number of games the home team won: ");
        File statsFile = new File(fileName);
        Scanner input2 = new Scanner(statsFile);


        input2.nextLine();
        input2.nextLine();

        while (input2.hasNextLine()) {
            String line = input2.nextLine();
            Scanner lineScan = new Scanner(line);

            while (lineScan.hasNext()) {
                if(lineScan.hasNextInt()) {
                    System.out.println(lineScan.nextInt()); 
                    break;
                }
                lineScan.next();
            }
            line = input2.nextLine();
        }
}

请尝试此代码。