[英]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);
}
您的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);}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.