【发布时间】:2020-10-15 19:27:26
【问题描述】:
我正在做一个练习,要求我读取 csv 格式的文件,并询问用户关于他希望程序查找的单词的输入。这是文档的格式,索引 0 和 1 是球队的名称,因此字符串和索引 2 和 3 是比赛的比分:
ENCE,Vitality,9,16
ENCE,Vitality,16,12
ENCE,Vitality,9,16
ENCE,Heroic,10,16
SJ,ENCE,0,16
SJ,ENCE,3,16
FURIA,NRG,7,16
FURIA,Prospects,16,1
起初,练习要求我编写一个程序来读取文档并打印某支球队打了多少场比赛。现在它要我写一个比较分数并打印该特定团队的输赢总数。我试图用一百万种不同的方式来做,有没有一种有效的方法来同时比较字符串和整数?
我的代码如下:
import java.nio.file.Paths;
import java.util.Scanner;
public class SportStatistics {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("File:");
String file = scan.nextLine();
System.out.println("Team:");
String team = scan.nextLine();
try ( Scanner reader = new Scanner(Paths.get(file))) {
int totalGames = 0;
int teamPoints = 0;
int otherPoints = 0;
int wins = 0;
int losses = 0;
while (reader.hasNextLine()) {
String info = reader.nextLine();
if (info.isEmpty()) {
continue;
}
String[] parts = info.split(",");
String homeN = parts[0];
String visitorN = parts[1];
int homeP = Integer.valueOf(parts[2]);
int visitorP = Integer.valueOf(parts[3]);
for (String part : parts) {
if (part.equals(team)) {
totalGames++;
}
if(homeN.equals(team)){
teamPoints = homeP;
otherPoints = visitorP;
if(teamPoints > otherPoints){
wins ++;
}else{
losses ++;
}
}
if(visitorN.equals(team)){
teamPoints = visitorP;
otherPoints = homeP;
if(teamPoints > otherPoints){
wins ++;
}else{
losses ++;
}
}
}
}
System.out.println("Games: " + totalGames);
System.out.println(wins);
} catch (Exception e) {
}
}
}
【问题讨论】: