Lester Koon
Lester Koon

Reputation: 19

Writing a program for a running competition using array

Write a program that asks for the names of three runners and the time, in minutes, it took each of them to finish a race. The program should display the names of the runners in the order that they finished.

The program works for whole numbers but is unable to arrange decimals. If I change the variable to integers, the input causes an error. Is there a solution for this?

import java.util.Arrays;
import java.util.Scanner;

    class Runners implements Comparable<Runners> {
        public String name;
        public double time;
        
        public Runners(String name, double time) {
            this.name = name;
            this.time = time;    
        }

        public String toString() {
            return String.format(" %s: %.2f minute(s) ", name, time);
        }

        public int compareTo(Runners other) {
            return (int) (this.time - other.time);
        }
    }
    
public class Question2 {

    public static void main(String[] args) {
        int count = 3;
        Runners[] runnersData = new Runners[count];
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < count; i++) {
            System.out.println("Enter runner's name and time taken in minutes: ");
            runnersData[i] = new Runners(input.next().strip(), input.nextDouble());
        }
        input.close();
        Arrays.sort(runnersData);
        System.out.println(Arrays.toString(runnersData));
    }
}

The unsorted decimals:
The unsorted decimals

The error if changed to int:
The error if changed to int

Upvotes: 1

Views: 707

Answers (1)

Christopher Schneider
Christopher Schneider

Reputation: 3915

compareTo doesn't require you to return the results of your arithmetic. You only have to return an integer signifying whether the items are equal, greater or less than.

public int compareTo(Runners other) {
    if(this.time == other.time)
       return 0;
    else if(this.time > other.time)
       return 1;
    else 
       return -1;
}

See the documentation on compareTo here. Also be aware that comparing doubles won't always behave the way you expect. I added the above for an example usage, but you can probably just return Double.compareTo(d1, d2). See those docs.

Upvotes: 3

Related Questions