【问题标题】:Line/Token based processing (java)基于行/令牌的处理(java)
【发布时间】:2015-10-22 21:03:20
【问题描述】:

我正在编写一个程序来从包含各种体育统计数据的文件中读取数据。每行都有关于特定游戏的信息,比如篮球。如果特定行包含“@”符号,则表示其中一支球队正在主场比赛。我正在尝试计算包含“@”的行并将其作为任一团队在主场比赛的比赛数输出给用户。第一个文件显示某支球队在家里打了 9 场比赛,但我的输出一直是 0 而不是 9。我该如何解决这个问题?

以下是相关代码:

public static void numGamesWithHomeTeam(String fileName) throws IOException{
    File statsFile = new File(fileName);
    Scanner input1 = new Scanner(statsFile);
    String line = input1.nextLine();
    Scanner lineScan = new Scanner(line);

    int count = 0;
    while(input1.hasNextLine()){
        if(line.contains("@")){
            count++;
            input1.nextLine();

        } else{
            input1.nextLine();
        }         
    } 
    System.out.println("Number of games with a home team: " + count);


}

【问题讨论】:

    标签: java file token file-processing


    【解决方案1】:

    您的 line 变量始终具有第一行的值。你应该在循环中设置行,类似的东西。

    while(input1.hasNextLine()){
            if(line.contains("@")){
                count++;
                line = input1.nextLine();
    
        } else{
                line = input1.nextLine();
            }       
    

    编辑:再看你的代码还有其他问题:最后一行从未被检查过。您不应该初始化 line(设置为 null)并在 nextLine() 之后进行检查:

    public static void numGamesWithHomeTeam(String fileName) throws IOException{
    File statsFile = new File(fileName);
    Scanner input1 = new Scanner(statsFile);
    String line = null;
    Scanner lineScan = new Scanner(line);
    
    int count = 0;
    while(input1.hasNextLine()){
        line = input1.nextLine();
        if(line.contains("@")){
            count++;
        }   
    } 
    System.out.println("Number of games with a home team: " + count);}
    

    【讨论】:

      猜你喜欢
      • 2015-11-17
      • 2019-06-01
      • 2012-10-19
      • 2016-01-23
      • 2015-03-28
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多