基于 Line/Token 的处理 (java)
Line/Token based processing (java)
我正在编写一个程序来从包含各种体育统计数据的文件中读取数据。每行都有关于特定游戏的信息,比如篮球。如果特定行包含“@”符号,则表示其中一支球队正在主场比赛。我正在尝试对包含“@”的行进行计数,并将其作为两支球队在主场比赛的比赛次数输出给用户。第一个文件显示某支球队在主场打了 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();
}
编辑:再看一遍您的代码还有其他问题:从未检查过最后一行。您不应该初始化行(设置为空)并在 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);}
我正在编写一个程序来从包含各种体育统计数据的文件中读取数据。每行都有关于特定游戏的信息,比如篮球。如果特定行包含“@”符号,则表示其中一支球队正在主场比赛。我正在尝试对包含“@”的行进行计数,并将其作为两支球队在主场比赛的比赛次数输出给用户。第一个文件显示某支球队在主场打了 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();
}
编辑:再看一遍您的代码还有其他问题:从未检查过最后一行。您不应该初始化行(设置为空)并在 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);}