【发布时间】:2016-10-11 21:24:38
【问题描述】:
我正在编写一个程序,我必须计算每个国家/地区的金牌数。输入将来自一个文件,我必须处理该文件。 第一行是国家代码,第二行是事件类型,第三行是事件。输入是这样的:
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
这是我编程的。我需要有关如何获得每个国家/地区的总金牌以及根据赛事类型获得金牌的帮助。 简而言之,我怎样才能获得上述所需的输出。 如果您在我的问题上需要帮助,我可以进一步解释。提示将不胜感激。
【问题讨论】:
-
简单的方法是拥有 2 张地图。第一个以国家/地区之类的字符串作为键,将奖牌数作为值的整数。第二个地图应该有一个事件字符串作为键和一个整数计数器作为值。比循环文件,您将总结国家和事件的奖牌。最后,在 2 个地图上的循环将打印您的输出。
-
感谢您的回复。问题是我还没有在地图上走得太远(这是我的下一个目标)。为了解决这个问题,我必须学习地图。我想知道的是,如果我不使用地图,我该怎么办。 @MarioAlexandroSantini
-
如果没有地图,您应该创建一个类 MedalCounter,其中包含 2 个属性、一个名称字符串和一个计数器,而不是创建 2 个 MedalCounter 数组,一份用于国家/地区,一份用于活动。
-
如此糟糕地循环遍历 GoldMedals 类型的获胜者数组,然后像这样:
countryMedalCounter[start] = new MedalCounter(winners[i].country, 1)我仍然不明白我是否喜欢这样做,它不会将具有不同事件的国家两次.除非我以错误的方式理解您的想法,否则这将破坏整个目的。 @MarioAlexandroSantini
标签: java arrays class object instance