gpt4 book ai didi

java - 奥运会java编码

转载 作者:行者123 更新时间:2023-12-01 06:08:23 24 4
gpt4 key购买 nike

我正在编写一个程序,我必须计算每个国家的金牌数。输入将来自一个文件,我必须处理该文件。 第一行是国家代码,第二行是事件类型,第三行是事件。输入如下:

CHN 
Diving
Women's 10m Platform
CAN
Rowing
Men's Eight
CHN
Rowing
Women's Quadruple Sculls

预期输出应如下所示:

Count of gold medallists by country:
CHN - 2
CAN - 1

Count of gold medallists by event type:
Diving - 1
Rowing - 2

好的,我已经创建了一类金牌,它将根据事件类型为每个国家/地区创建一个新的实例对象。我的代码在这里:

class GoldMedals {
private String country;
private String eventType;
private String event;
private int medalCount;

public GoldMedals(String name, String type, String event) {
this.country = name;
this.eventType = type;
this.event = event;
medalCount = 1;
}

public boolean matchDetails(String countryName, String type){
return (country.equals(countryName) && eventType.equals(type));
}

我的主要方法在这里:

try {
input = new BufferedReader(new FileReader ("textfile.txt"));
country = input.readLine();
while(country!=null) {
eventType = input.readLine();
event = input.readLine();
match = findMatch(winners, size, country, eventType);
if(match == null) {
winners[size] = new GoldMedals(country, eventType, event);
size++;
//match.addMedal();
} //else {

//match.addMedal();
//}
//match.addMedal();
country = input.readLine();
}

input.close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());

我还添加了一个静态方法,它将确保我们不会创建已经存在的对象。 (冗余对象)

public static GoldMedals findMatch(GoldMedals[] winners, int size, String country, String type) {
GoldMedals result = null;
int pos;

pos = 0;
while (pos < size && result == null) {
if (winners[pos].matchDetails(country, type)) {
result = winners[pos];
} else {
pos++;
}
}
return result;
}

我想知道的是如何获得所需的输出。因为现在我得到这个输出:

ITA- 1- Fencing- Women's Individual Foil
POL- 1- Rowing- Men's Quadruple Sculls
KEN- 1- Athletics- Men's Marathon
CHN- 1- Diving- Men's 3m Springboard
TUN- 1- Swimming- Men's 1500m Freestyle
CHN- 1- Canoe/Kayak - Flatwater- Canoe Double (C2) 500m Men
CHN- 1- Diving- Men's Synchronised 3m Springboard
USA- 1- Gymnastics Artistic- Women's Individual All-Around
RUS- 1- Synchronized Swimming- Duet

这就是我编写的程序。我需要帮助了解如何获得每个国家的金牌总数以及根据赛事类型获得的金牌。 简而言之,我怎样才能获得上面所需的输出。如果您需要帮助解决我的问题,我可以进一步解释。提示将不胜感激。

最佳答案

删除medalCount field 。您的类应该只代表传入的数据。

然后您想要构建两个 Map<String, Long>对象,其中键是国家/地区代码或事件类型,值是键的计数。

使用 Java 8 流,这相当简单:

List<GoldMedals> allMedals = loadMedalsFromFile();

Map<String, Long> byCountry = allMedals.stream()
.collect(Collectors.groupingBy(GoldMedals::getCountry,
Collectors.counting()));

Map<String, Long> byEventType = allMedals.stream()
.collect(Collectors.groupingBy(GoldMedals::getEventType,
Collectors.counting()));

关于java - 奥运会java编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39986995/

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