Open littlehug opened 6 years ago
import java.util.ArrayList; import java.util.Comparator;
public class SortStudents {
public static void main(String[] args) {
// Create a list of students
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();
}
}
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
Input Format
There is one number N in the first line indicating the number of students. The next N lines are students’ names, heights and weights. Each line contains one string and two integers. The string is student’s name (length < 64). The first number is student’s height. The second number is student’s weight.
Output Format
Print sorted data in different line. The output format for each student is ‘name height weight’.
Sample Input 1
Sample Output 1
Sample Input 2
Sample Output 2