import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collec
ID: 3902873 • Letter: I
Question
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class PersonQueue {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue<Person> personQ = new LinkedList<>();
Scanner in = new Scanner(System.in);
int i;
try {for (i=0; i<5; i++)
{
System.out.println("Please enter the first name of Person number " + (i+1));
String firstName = in.nextLine();
System.out.println("Please enter the last name of Person number " + (i+1));
String lastName = in.nextLine();
System.out.println("Please enter the age of Person number " + (i+1));
int age=in.nextInt();
in.nextLine();
personQ.add(new Person(firstName,lastName,age));}}
catch (InputMismatchException e) {throw new InputMismatchException ("Invalid age format");}
List l =(List) personQ;
Collections.sort(l, Person.COMPARE_BY_AGE );
for (Person person : personQ) {
System.out.println("Person Name Sorted by Age in Descending order is: " + person.getfirstName() + " " + person.getlastName() + " " + person.getage());
}
Collections.sort(l,Person.COMPARE_BY_NAME );
for (Person person : personQ) {
System.out.println("Person Name Sorted by Name in Descending order is: " + person.getfirstName() + " " + person.getlastName() + " " + person.getage());
}}
}
Need help adding the exception handler for invalid integers added to age input thanks
Explanation / Answer
import java.util.Comparator; public class Person { public static final Comparator COMPARE_BY_AGE = new Comparator() { @Override public int compare(Person o1, Person o2) { return Integer.compare(o1.age, o2.age); } }; public static final Comparator COMPARE_BY_NAME = new Comparator() { @Override public int compare(Person o1, Person o2) { return (o1.firstName + o1.lastName).compareTo(o2.firstName + o2.lastName); } }; private String firstName, lastName; private int age; public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getfirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getlastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getage() { return age; } public void setAge(int age) { this.age = age; } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.