我获得了一个冬季奥运会的文本文件。 它包含团队,竞争对手的名字和分数。
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的球队按降序显示?
答案 0 :(得分:0)
您必须创建一个对hashmap进行排序的方法。
这篇文章中的示例方法很少: Sorting HashMap by values
答案 1 :(得分:0)
Comparator
的类,可以根据Map.Entry<String,Double>
部分比较两个Double
个对象。TreeSet<Map.Entry<String,Double>>
,它是一个有序集的实现。addAll
的{{1}}方法添加TreeSet
中的值。另一种方法是将该集复制到totalScore.entrySet()
,然后使用List<Map.Entry<String,Double>>
对其进行排序。它仍然需要一个比较器对象!