0

I am working on a project to read data in from a text file regarding different athletes' scores at the winter Olympics. I have successfully been able to find each country's total score by comparing each athlete with their country and adding it to a total. Each of these totals are stored in doubles: FRA, CHN, UKR, GER, RUS, CAN, ITA, USA, JPN, and GBR. (All representing different countries)

So now I have a bunch of values stored as doubles that I need to sort in descending order. I know I could just put the doubles into an array and sort it, but I will lose the name of the country associated to each value. In PHP I could simply put it into an associative array and sort it - but unfortunately I have a very poor understanding of java and don't have a clue what to do. I would appreciate it if someone could at least point me in the right direction.

The output needs to Display the countries name and it's score in descending order.

xlm
  • 6,854
  • 14
  • 53
  • 55

1 Answers1

2
public class Score implements Comparable<Score>{

    private String country;
    private int score;

    //write getters, setters

    public int compareTo(Score otherScore){
        return otherScore.score - this.score   // for descending
            // return this.score - otherScore.score for assending

    }
}

You can create array of Score objects and pass it to Array.sort(array); Now the sorting criteria for these objects are the score.

Example in detail: http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

Chamil
  • 805
  • 5
  • 12
  • Subtracting both scores **should** be OK, but it's probably a better practice to use Java's built-in: `Integer.compare (score, otherScore)` – Mureinik Mar 04 '14 at 07:05