gpt4 book ai didi

java - 基于行/ token 的处理 (java)

转载 作者:行者123 更新时间:2023-12-02 04:16:13 26 4
gpt4 key购买 nike

我正在编写一个程序来从包含各种体育统计数据的文件中读取数据。每行都有有关特定比赛(例如篮球)的信息。如果某一行包含“@”符号,则表示其中一支球队正在主场比赛。我正在尝试计算包含“@”的行,并将其作为任一球队在主场比赛的比赛数输出给用户。第一个文件显示某个球队在主场进行了 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);


}

最佳答案

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

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

关于java - 基于行/ token 的处理 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33290709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com