use java Create a program that uses a priority queue to collect user name and us
ID: 3820625 • Letter: U
Question
use java
Create a program that uses a priority queue to collect user name and user age from a system user and then displays those values in ascending order (regardless of the order in which they are added).
import java.util.PriorityQueue;
public class MIKESQCOMPARATORMAIN
{
public static void main(String[] args)
{
MyComparator comparator = new MyComparator();
PriorityQueue<Employee> pQueue = new PriorityQueue<Employee>(7, comparator);
pQueue.offer(new Employee("AAA", 15000));
pQueue.offer(new Employee("BBB", 12000));
pQueue.offer(new Employee("CCC", 7500));
pQueue.offer(new Employee("DDD", 17500));
pQueue.offer(new Employee("EEE", 21500));
pQueue.offer(new Employee("FFF", 29000));
pQueue.offer(new Employee("GGG", 14300));
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
}
}
Explanation / Answer
JAVA :
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Employee{
public String name;
public int age;
Employee(String name, int age){
this.name = name;
this.age = age;
}
@Override
public String toString(){
return name+" "+age;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner obj = new Scanner(System.in);
System.out.println("Enter number of entries");
int n = obj.nextInt();
PriorityQueue<Employee> pq = new PriorityQueue<Employee>(n, new Comparator<Employee>(){
public int compare(Employee a, Employee b){
//Compare with age
return Integer.compare(a.age,b.age);
//Compare with the names
// return a.name.compareTo(b.name);
}
});
for(int i=0;i<n;i++){
String name = obj.next();
int age = obj.nextInt();
pq.add(new Employee(name,age));
}
for(int i=0;i<n;i++){
System.out.println(pq.poll());
}
}
}
INPUT :
5
Genny 38
Lizz 35
Siva 48
Andrea 27
Prudhvi 21
OUTPUT :
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.