Running the race

The problem

Write a program that asks for the names of runners and the time it took each of them to finish a race. The program should display the names of the runners in the order that they finsihed. Use a comparator and Collections.sort.

Breaking it down

Create a Runner class

class Runner {
    
    private String name;
    private double timeToCompleteRace;
    
    public Runner(String name, double timeToCompleteRace) {
        super();
        this.name = name;
        this.timeToCompleteRace = timeToCompleteRace;
    }
    
    @Override
    public String toString() {
        
        return Objects.toStringHelper(this)
                .add("name", name)
                .add("time to complete", timeToCompleteRace)
                .toString();
    }

    public String getName() {
        return name;
    }

    public double getTimeToCompleteRace() {
        return timeToCompleteRace;
    }
    
}

Initalize variables

List<Runner> race = Lists.newArrayList();

// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);

String name;
double raceTime;

RunningTheRace runningTheRace = new RunningTheRace();

Get user input

do {
    System.out.print("Enter name: ");
    name = keyboard.next();
    
    System.out.print("Enter race time:  (-1 to exit):  ");
    raceTime = keyboard.nextDouble();
    
    if (!name.equals("-1")) {
        race.add(runningTheRace.new Runner(name,  raceTime));  
    }
    
} while (!name.equals("-1"));

Create comparator

/**
 * Comparator byRaceTime 
 */
static Comparator<Runner> byRaceTime = new Comparator<Runner>() {
    public int compare(Runner left, Runner right) {
        return Double.compare(left.getTimeToCompleteRace(), right.getTimeToCompleteRace()) ; // use your logic
    }
};

Sort runners

Collections.sort(race, byRaceTime);

Display output

System.out.println("Name" + "\t" + "Time");
System.out.println("---------------------");

for (Runner runner : race) {
    System.out.println(runner.getName() + "\t" + runner.getTimeToCompleteRace());
}

Output

Enter name: jack
Enter race time:  (-1 to exit):  2343
Enter name: jimmy
Enter race time:  (-1 to exit):  2344
Enter name: cindy
Enter race time:  (-1 to exit):  9384
Enter name: 
-1
Enter race time:  (-1 to exit):  -1
Name    Time
---------------------
jack    2343.0
jimmy   2344.0
cindy   9384.0

Level Up

  • Pretty up the output
  • Fix bug w/ -1 as the exit
  • Format time in seconds, minutes and hours