Programming Exercise(s): refresher Write a program in Java that asks for user in
ID: 3560889 • Letter: P
Question
Programming Exercise(s): refresher
Write a program in Java that asks for user input for the names of 5 people and their ages. Then in the display list the 5 students in order by age first and name second.
The following requirements must be met.
1) Use Blue Jay
2) Must have a class
3) Must have a constructor
4) Must create an object to hold the name and age of the person
5) Must use at least 2 methods other, than the constructor method.
6) Must use proper comments
7) Must have a main method
8) Must compile with no errors.
Explanation / Answer
Student Class:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Main Method :
import java.util.*;
public class SortingAges {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<Student>(5);
// Scanner accepts input from the user
Scanner scanner = new Scanner(System.in);
for (int i =1; i<6 ;i++){
System.out.println("Enter student "+i+" name:");
String name = scanner.next();
System.out.println("Enter student "+i+" age:");
int age = scanner.nextInt();
Student student = new Student(name,age);
// Each student object is created and added to the student list
studentList.add(student);
}
/**
* Collections.sort() is a method provided by Java that sorts the objects in the list
* based on comparator. The sorting algorithm is used here is modified merge sort.
*/
Collections.sort(studentList,new Comparator<Student>() {
@Override
public int compare(Student student, Student student1) {
return student.getAge() - student1.getAge();
}
});
System.out.println("The sorted student list: ");
for (int i=0; i< studentList.size();i++) {
System.out.println(studentList.get(i).getName());
}
}
}
Please revert back if you need more.
You can copy the same files in BlueJ and run it.
Thanks,
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.