[英]Token and line processing Java
我正在編寫一個程序,該程序從包含各種籃球運動統計數據的文本文件中讀取數據。 每行(在兩個標題行之后)對應於一場特定的比賽和每支球隊的得分,其中還有一些其他字符串。 我正在嘗試使用掃描儀讀取每場比賽的 int 分數,將它們存儲在變量中,然后比較它們以確定哪支球隊贏得了那場比賽,以便我可以在稍后的程序中增加獲勝次數。 我想出了如何按順序讀取所有整數,但我無法弄清楚如何讀取一行中的兩個整數,將它們存儲為變量,比較它們,然后繼續下一行/游戲。
這是相關的方法:
public static void numGamesHTWon(String fileName)throws FileNotFoundException{
System.out.print("Number of games the home team won: ");
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
input1.nextLine();
input1.nextLine();
while (input1.hasNext()) {
if (input1.hasNextInt()) {
int x = input1.nextInt();
System.out.print(x);
input1.next();
} else {
input1.next();
}
}
文本文件中的幾行:
NCAA 女子籃球
2011 - 2012
2007-11-11 賴斯 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 田納西 76 查塔努加 56
2007-11-11 密西西比街 76 百年 57
2007-11-11 ETSU 75 Delaware St 72 O1 季前賽 NIT
逐行讀取文件。 然后將該行拆分為 String[]。 由於您知道分數在每一行的位置,因此您可以輕松地從數組中解析這些值並進行比較。 你能分享幾行你的輸入嗎? 然后我可以給你看確切的代碼
你可以嘗試類似的東西
String[] parts = str.split("\\D+");
其中 str 是您剛剛閱讀的行。 現在部分數組將包含字符串中的所有數字。 只需通讀數組,解析為 int 並進行比較。 請注意,此數組中的前三個條目將對應於日期,因此請忽略它們。
例如
String[] parts = "2007-11-11 Mississippi St 76 Centenary 57".split("\\D+");
for (String g: parts)
System.out.println(g);
打印出來
2007
11
11
76
57
所以現在你可以只取最后兩個值並進行比較
while (input1.hasNextLine()) {
String line = input1.nextLine();
String[] parts = line .split("\\D+");
int score1 = Integer.parseInt(parts[parts.length-2]);
int score2 = Integer.parseInt(parts[parts.length-1]);
/*now compare score1 and score2 and do whatever...*/
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.