Java 将用户输入的值与存储在数组中的值进行比较?
目前,我有一个文件读取器,它逐行读取文件中的数据,并进行检查以确保输入的数据符合要求的格式,如果符合要求,则会将它们添加到数组中,并将输出数据添加到控制台中。我想做的是,让用户可以进入一个特定的团队,它将通过文件,只记录相关的数据给该团队,但我不知道我将如何做到这一点。以下是我的代码,它将记录和打印文本文件中的数据:Java 将用户输入的值与存储在数组中的值进行比较?,java,arrays,Java,Arrays,目前,我有一个文件读取器,它逐行读取文件中的数据,并进行检查以确保输入的数据符合要求的格式,如果符合要求,则会将它们添加到数组中,并将输出数据添加到控制台中。我想做的是,让用户可以进入一个特定的团队,它将通过文件,只记录相关的数据给该团队,但我不知道我将如何做到这一点。以下是我的代码,它将记录和打印文本文件中的数据: String hteam; String ateam; int hscore; int ascore; int totgoals = 0;
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
我的问题是如何设置,以便用户可以输入团队名称,然后将其与hteam或ateam的名称进行比较,并继续读取循环的每一行。当您对计算文件中团队的匹配数量感兴趣时,我会使用
映射。首先,填充地图:
Map<String, Integer> teams = new HashMap<>();
String team = "team A";
if(teams.containsKey(team)) {
teams.put(team, teams.get(team) + 1);
} else {
teams.put(team, 1);
}
因此,您无法输入团队名称,然后比较什么?@hoyah_hayoh用户将输入团队名称&在读取到系统中的文本文件中,每行都有团队名称,因此它将检查这些名称是否匹配。如果它这样做了,那么它将增加一个特定的数字来标记它匹配了多少次。如果我们理解了正确的问题,这就是正确的方法。最好不要将它定义为HashMap
,而是定义为Map
。啊,我认为这是有意义的,而不是我尝试的方式。谢谢。
String userTeam = "...";
if(teams.containsKey(userTeam)) {
System.out.println(userTeam + ": " + teams.get(userTeam));
} else {
System.out.println(userTeam + " unknown");
}