简体   繁体   English

扫描器/令牌错误Java

[英]Scanner/Token error java

I'm writing a program that reads sports data from a text file. 我正在编写一个从文本文件读取体育数据的程序。 Each line has strings and ints mixed together, and I'm trying to read just the scores of the teams. 每行都将字符串和整数混合在一起,我正在尝试仅读取团队的分数。 However, even though the lines have ints, the program immediately goes to the else statement without printing out the scores. 但是,即使这些行具有整数,该程序仍会立即转到else语句,而不会输出分数。 I have the two input2.nextLine() statements so that it skips two header lines that have no scores. 我有两个input2.nextLine()语句,因此它跳过了没有分数的两个标题行。 How can I fix this? 我怎样才能解决这个问题?

Here's the code: 这是代码:

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();



        }
    }
}

Here is the top of the text file: 这是文本文件的顶部:

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

Method hasNextInt() try to check immediate string is int ? 方法hasNextInt()尝试检查立即字符串是否为int? . So that condition is not working. 因此该条件不起作用。

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();
        }
}

Please try this code. 请尝试此代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM