Created
December 7, 2019 04:28
-
-
Save AmbroseNTK/464721c3e8a42eb19570a506a3afa2db to your computer and use it in GitHub Desktop.
Java create student list and sorting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Comparator; | |
public class Student { | |
private String id; | |
private String name; | |
private double gpa; | |
public String getId() { | |
return id; | |
} | |
public void setId(String id) { | |
this.id = id; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public double getGPA() { | |
return gpa; | |
} | |
public void setGPA(double gpa) { | |
if (gpa >= 0 && gpa <= 4.0) { | |
this.gpa = gpa; | |
} else { | |
this.gpa = 0; | |
} | |
} | |
public Student(String id, String name, double gpa) { | |
setId(id); | |
setName(name); | |
setGPA(gpa); | |
} | |
} | |
public class Program { | |
public static void main(String[] args) { | |
int numOfStudent = 20; | |
ArrayList<Student> studentList = new ArrayList<>(); | |
for (int i = 0; i < numOfStudent; i++) { | |
studentList.add(new Student("SID" + i, "Student#" + i, i)); | |
} | |
studentList.sort(new Comparator<Student>() { | |
@Override | |
public int compare(Student o1, Student o2) { | |
if (o1.getGPA() == o2.getGPA()) { | |
return 0; | |
} | |
if (o1.getGPA() > o2.getGPA()) { | |
return -1; | |
} | |
return 1; | |
} | |
}); | |
String format = "%7s|%-15s|%7s"; | |
System.out.println(String.format(format, "SID", "Name", "GPA")); | |
for (int i = 0; i < studentList.size(); i++) { | |
System.out.println(String.format(format, studentList.get(i).getId(), studentList.get(i).getName(), | |
studentList.get(i).getGPA())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment