pangfengliu / programmingtasks

programming tasks from my courses
68 stars 17 forks source link

Height and Weight #361

Open littlehug opened 6 years ago

littlehug commented 6 years ago

Write a program to sort students according to their BMI, weight, height, and names.

Task Description

You are given N students’ names, heights and weights and you need to sort them. We will sort them according to the BMI first, which is defined as the weight (in kilogram) divided by the square of the height (in meter). If two students have the same BMI, then we compare the weight, if they are still the same then we compare the height. If they are still the same we compare the names (in dictionary order). It is guaranteed that no two students have the same name. Note that you need to use floating point numbers to compute BMI.

Subtask

parksonwu commented 1 year ago

import java.util.ArrayList; import java.util.Comparator;

public class SortStudents { public static void main(String[] args) { // Create a list of students ArrayList students = new ArrayList<>();

    // Populate the list with student objects
    students.add(new Student("John", 1.80, 80.0));
    students.add(new Student("Alice", 1.70, 65.5));
    students.add(new Student("Bob", 1.75, 70.0));
    students.add(new Student("Carol", 1.60, 50.0));

    // Sort students according to BMI, weight, height, and name
    students.sort(Comparator.comparingDouble(Student::getBMI)
            .thenComparingDouble(Student::getWeight)
            .thenComparingDouble(Student::getHeight)
            .thenComparing(Student::getName));

    // Print the sorted list of students
    for (Student s : students) {
        System.out.println(s);
    }
}

}

class Student { private String name; private double height; private double weight;

public Student(String name, double height, double weight) {
    this.name = name;
    this.height = height;
    this.weight = weight;
}

public String getName() {
    return name;
}

public double getHeight() {
    return height;
}

public double getWeight() {
    return weight;
}

public double getBMI() {
    return weight / Math.pow(height, 2);
}

@Override
public String toString() {
    return "Name: " + name + ", Height: " + height + ", Weight: " + weight + ", BMI: " + this.getBMI();
}

}