gpt4 book ai didi

java - token 和行处理Java

转载 作者:行者123 更新时间:2023-11-30 10:55:35 26 4
gpt4 key购买 nike

我正在编写一个程序,从包含各种篮球运动统计数据的文本文件中读取数据。每行(在两个标题行之后)对应一场特定的比赛和每支球队的得分,其中还有一些其他字符串。我正在尝试使用扫描仪读取每场比赛的积分,将它们存储在变量中,然后比较它们以确定哪支球队赢得了那场比赛,以便我可以稍后在程序中增加胜利。我想出了如何按顺序读取所有整数,但我不知道如何读取一行中的两个整数,将它们存储为变量,比较它们,然后继续下一行/游戏。

相关方法如下:

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 @温思罗普 54 O1
2007-11-11 @S Dakota St 93 加州大学河滨分校 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 是您刚刚阅读的行。现在 parts 数组将包含字符串中的所有数字。只需读取数组,解析为 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...*/
}

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

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