我收到了一个冬奥会项目的文本文件。它包含参赛队伍、参赛者姓名和分数。
FRAMae Berenice MEITE 455.455
CHNKexin ZHANG 454.584
UKRNatalia POPOVA 453.443
GERNathalie WEINZIERL 452.162
RUSEvgeny PLYUSHCHENKO 191.399
CANPatrick CHAN 189.718
CHNHan YAN 185.527
CHNCheng & Hao 271.018
ITAStefania & Ondrej 270.317
USAMarissa & Simon 264.256
GERMaylin & Daniel 260.825
FRAFlorent AMODIO 179.936
GERPeter LIEBERS 179.615
ect....
唯一重要的数字是数字中的最后一位。对于每支球队,我需要将他们的总分加在一起,并显示前5名球队。
到目前为止的代码:
public class project2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String[] array = new String[41];
String[] info = new String [41];
String[] stats = new String[41];
String[] team = new String[41];
//.txt file location
FileInput fileIn = new FileInput();
fileIn.openFile("C:\Users\O\Desktop\turn in\team.txt");
//txt file to array
int i=0;
String line = fileIn.readLine();
array[i] = line; i++;
while (line != null) {
line = fileIn.readLine();
array[i] = line; i++;
}
System.out.println(array[1]);
//Splitting up team/competitor name/score
for (int j =0; j< 40; j++){
team[j] = array[j].substring (0, 3).trim ();
info[j] = array[j].substring (3, 30).trim ();
stats[j] = array[j].substring (36).trim ();
}
//random outputs ive been using fore testing.
System.out.println(team[1]);
System.out.println(info[1]);
System.out.println(stats[1]);
MyObject ob = new MyObject();
ob.setText(info[0]);
ob.setNumber(7, 23);
ob.setNumber(3, 456);
System.out.println("Text is " + ob.getText() + " and number 3 is " + ob.getNumber(7));
for (int j =0; j< 40; j++){
team[j] = array[j].substring (0, 3).trim ();
info[j] = array[j].substring (3, 30).trim ();
stats[j] = array[j].substring (36).trim ();
}
//team and score in hashmap
double[] statsDub = new double[40];
for (int k =1; k < 40; k++){
statsDub[k] = Double.parseDouble(stats[k]);
}
Map<String,Double> totalScore = new HashMap<>();
for (int j =0; j< 40; j++){
Double tmp = totalScore.get (team[j]);
if (tmp != null)
{
totalScore.put(team[j], statsDub[j]+tmp);
}
else
totalScore.put(team[j], statsDub[j]);
}
// Get a set of the entries
Set set = totalScore.entrySet();
// Get an iterator
Iterator i1 = set.iterator();
// Display elements
while(i1.hasNext()) {
Map.Entry me = (Map.Entry)i1.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}}}
//if (totalScore.containsKey("COUNTRYNAME"))
// totalScore.put("COUNTRYNAME", totalScore.get("COUNTRYNAME") + playerScore);
//else
// totalScore.put("COUNTRYNAME",0);
我得到这个输出:
GER: 17.0
USA: 27.0
ITA: 23.0
RUS: 37.0
CHN: 20.0
JPN: 24.0
FRA: 17.0
CAN: 32.0
UKR: 10.0
GBR: 8.0
我怎么能只按降序显示前5名的球队呢?
- 创建一个实现
Comparator
的类,该类可以基于Double
部分在两个Map.Entry<String,Double>
对象之间进行比较 - 使用该比较器创建一个
TreeSet<Map.Entry<String,Double>>
,它是有序集的实现 - 现在使用
TreeSet
的addAll
方法将从totalScore.entrySet()
获得的集合中的值相加 - 对结果集进行迭代,保留一个整数变量来计算迭代次数,并在5处停止
另一种选择是将集合复制到List<Map.Entry<String,Double>>
,然后使用Collections.sort
对其进行排序。它仍然需要一个comparator对象!