Question

In: Computer Science

Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static...

Add comments to the following code:

PeopleQueue.java

import java.util.*;
public class PeopleQueue {

    public static void main(String[] args) {
        PriorityQueue<Person> peopleQueue = new PriorityQueue<>();
        Scanner s = new Scanner(System.in);
        String firstNameIn;
        String lastNameIn;
        int ageIn = 0;
        int count = 1;
        boolean done = false;

        System.out.println("Enter the first name, last name and age of 5 people.");
        while(peopleQueue.size() < 5) {
            System.out.println("Enter a person");
            System.out.print("First Name: ");
            firstNameIn = s.nextLine();
            System.out.print("Last Name: ");
            lastNameIn = s.nextLine();
            System.out.print("Age: ");
            while(!done) {
                try {
                    ageIn = Integer.parseInt(s.nextLine());
                    done = true;
                } catch (NumberFormatException e) {
                    System.out.println("Error: Please enter a number for age");
                    System.out.print("Age: ");
                }
            }
            Person person = new Person(firstNameIn, lastNameIn, ageIn);
            peopleQueue.add(person);
            System.out.println("Added to queue: " + firstNameIn + " " + lastNameIn + ", Age: " + ageIn + "\n");
            done = false;
        }

        NameCompare nameCompare = new NameCompare();
        List<Person> people = new ArrayList(peopleQueue);
        Collections.sort(people, nameCompare);

        System.out.println("Sorted by Last Name\n");
        for (int i = 0; i < people.size(); i++) {
            System.out.println("Name: " + people.get(i).getFirstName() + " "
                                        + people.get(i).getLastName() + ", Age: "
                                        + people.get(i).getAge());
        }


        System.out.println("\nSorted by Age and removed from queue\n");
        while (!peopleQueue.isEmpty()) {
            System.out.println("Removed Person " + count + " -" + peopleQueue.remove());
            count++;
        }
    }
}


Person.java

public class Person implements Comparable<Person> {

    private int age;
    private String firstName;
    private String lastName;

    public Person(String first, String last, int theirAge) {
        this.firstName = first;
        this.lastName = last;
        this.age = theirAge;
    }

    public String getFirstName() {
        return this.firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String last) {
        this.lastName = last;
    }

    public int getAge() {
        return this.age;
    }

    @Override
    public int compareTo(Person person) {
        if(this.equals(person))
            return 0;
        else if(getAge() < person.getAge())
            return 1;
        else
            return -1;
    }

    public String toString() {
        return " Name: " + getFirstName() + " " + getLastName() + ", Age: " + getAge();
    }


}


NameCompare.java

import java.util.Comparator;
public class NameCompare implements Comparator<Person> {

    public int compare(Person p1, Person p2) {
        int i = p1.getLastName().compareTo(p2.getLastName());
        if(i != 0) return -i;
        return i;
    }
}

Solutions

Expert Solution

Here is the commented code for this problem. Comments are included in every important statements, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// PeopleQueue.java

import java.util.*;

public class PeopleQueue {

      public static void main(String[] args) {

            // creating a PriorityQueue of Person objects

            PriorityQueue<Person> peopleQueue = new PriorityQueue<Person>();

            // creating a Scanner for reading keyboard input

            Scanner s = new Scanner(System.in);

            // declaring needed variables to represent data fields of a person

            String firstNameIn;

            String lastNameIn;

            int ageIn = 0;

            int count = 1;

            // inner loop controller

            boolean done = false;

            // asking for inputs for 5 persons

            System.out

                        .println("Enter the first name, last name and age of 5 people.");

            // looping until queue contains at least 5 records

            while (peopleQueue.size() < 5) {

                  // prompting and getting first and last names

                  System.out.println("Enter a person");

                  System.out.print("First Name: ");

                  firstNameIn = s.nextLine();

                  System.out.print("Last Name: ");

                  lastNameIn = s.nextLine();

                  System.out.print("Age: ");

                  // looping until done variable is true

                  while (!done) {

                        // reading a String, converting to integer

                        try {

                              ageIn = Integer.parseInt(s.nextLine());

                              // parsing is successful,setting done to true, inner loop

                              // will not run next time

                              done = true;

                        } catch (NumberFormatException e) {

                              System.out.println("Error: Please enter a number for age");

                              System.out.print("Age: ");

                        }

                  }

                  // creating a person

                  Person person = new Person(firstNameIn, lastNameIn, ageIn);

                  // adding to queue

                  peopleQueue.add(person);

                  // displaying added data

                  System.out.println("Added to queue: " + firstNameIn + " "

                              + lastNameIn + ", Age: " + ageIn + "\n");

                  // setting done to false for next iteration of inner loop

                  done = false;

            }

            // creating a NameCompare object

            NameCompare nameCompare = new NameCompare();

            // creating a List of person objects from queue

            List<Person> people = new ArrayList(peopleQueue);

            // using NameCompare comparator, sorting person objects by name

            Collections.sort(people, nameCompare);

            System.out.println("Sorted by Last Name\n");

            // displaying list sorted by name

            for (int i = 0; i < people.size(); i++) {

                  System.out.println("Name: " + people.get(i).getFirstName() + " "

                              + people.get(i).getLastName() + ", Age: "

                              + people.get(i).getAge());

            }

            // now looping and printing the list of persons sorted by age from queue

            // until queue is empty. Since Person class's compareTo method compare

            // by age, the elements in priority queue will be automatically sorted

            // order by age

            System.out.println("\nSorted by Age and removed from queue\n");

            while (!peopleQueue.isEmpty()) {

                  System.out.println("Removed Person " + count + " -"

                              + peopleQueue.remove());

                  count++;

            }

      }

}

// Person.java

public class Person implements Comparable<Person> {

      /**

      * attributes

      */

      private int age;

      private String firstName;

      private String lastName;

      /**

      * constructor taking values for all fields

      */

      public Person(String first, String last, int theirAge) {

            this.firstName = first;

            this.lastName = last;

            this.age = theirAge;

      }

      /**

      * getter for first name

      */

      public String getFirstName() {

            return this.firstName;

      }

      /**

      * getter for last name

      */

      public String getLastName() {

            return this.lastName;

      }

      /**

      * setter for last name

      */

      public void setLastName(String last) {

            this.lastName = last;

      }

      /**

      * getter for age

      */

      public int getAge() {

            return this.age;

      }

      /**

      * compares two Person objects by age in descending order, returns a

      * negative value if this person comes before other, 0 if both have same

      * ordering, positive value if other person comes before this person.

      */

      @Override

      public int compareTo(Person person) {

            if (this.equals(person))

                  return 0; // same objects

            else if (getAge() < person.getAge())

                  return 1; // this person comes after other

            else

                  return -1; // this person comes before other

      }

      /**

      * returns a String containing person details

      */

      public String toString() {

            return " Name: " + getFirstName() + " " + getLastName() + ", Age: "

                        + getAge();

      }

}

// NameCompare.java

import java.util.Comparator;

/**

* comparator class that compares two Person objects by last names

*/

public class NameCompare implements Comparator<Person> {

      /**

      * this method returns a negative value if p1 comes before p2, 0 if p1 and

      * p2 have same ordering, positive value if p2 comes before p1. This method

      * is used to sort Person objects by reverse alphabetical order of their

      * lastnames

      */

      public int compare(Person p1, Person p2) {

            // comparing last names

            int i = p1.getLastName().compareTo(p2.getLastName());

            if (i != 0)

                  return -i; // i is alphabetical order, -i yields reverse

                                    // alphabetical order

            return i;

      }

}


Related Solutions

Add code to the Account class and create a new class called BalanceComparator. import java.util.*; public...
Add code to the Account class and create a new class called BalanceComparator. import java.util.*; public final class Account implements Comparable {     private String firstName;     private String lastName;     private int accountNumber;     private double balance;     private boolean isNewAccount;     public Account(             String firstName,             String lastName,             int accountNumber,             double balance,             boolean isNewAccount     ) {         this.firstName = firstName;         this.lastName = lastName;         this.accountNumber = accountNumber;         this.balance = balance;         this.isNewAccount = isNewAccount;     }     /**      * TO DO: override equals      */     @Override     public boolean equals(Object other) {...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private String name;    private double price;    private int bulkQuantity;    private double bulkPrice;    /***    *    * @param name    * @param price    * @param bulkQuantity    * @param bulkPrice    */    public Item(String name, double price, int bulkQuantity, double bulkPrice) {        this.name = name;        this.price = price;        this.bulkQuantity = bulkQuantity;        this.bulkPrice = bulkPrice;   ...
Please add comments to this code! Item Class: import java.text.NumberFormat; public class Item {    private...
Please add comments to this code! Item Class: import java.text.NumberFormat; public class Item {    private String name;    private double price;    private int bulkQuantity;    private double bulkPrice;    /***    *    * @param name    * @param price    * @param bulkQuantity    * @param bulkPrice    */    public Item(String name, double price, int bulkQuantity, double bulkPrice) {        this.name = name;        this.price = price;        this.bulkQuantity = bulkQuantity;        this.bulkPrice = bulkPrice;   ...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final ArrayList<ItemOrder> itemOrder;    private double total = 0;    private double discount = 0;    ShoppingCart() {        itemOrder = new ArrayList<>();        total = 0;    }    public void setDiscount(boolean selected) {        if (selected) {            discount = total * .1;        }    }    public double getTotal() {        total = 0;        itemOrder.forEach((order) -> {            total +=...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog { String catalog_name; ArrayList<Item> list; Catalog(String cs_Gift_Catalog) { list=new ArrayList<>(); catalog_name=cs_Gift_Catalog; } String getName() { int size() { return list.size(); } Item get(int i) { return list.get(i); } void add(Item item) { list.add(item); } } Thanks!
In java. Please explain. Consider the following program: } import java.util.*; public class Chapter7Ex12 { static...
In java. Please explain. Consider the following program: } import java.util.*; public class Chapter7Ex12 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { double num1; double num2; System.out.print("Enter two integers: "); num1 = console.nextInt(); num2 = console.nextInt(); System.out.println(); if (num1 != 0 && num2 != 0) System.out.printf("%.2f\n", Math.sqrt(Math.abs(num1 + num2 + 0.0))); else if (num1 != 0) System.out.printf("%.2f\n", Math.floor(num1 + 0.0)); else if (num2 != 0) System.out.printf("%.2f\n",Math.ceil(num2 + 0.0)); else System.out.println(0); }} a. What is the...
I'm getting an error for this code? it won't compile import java.util.*; import java.io.*; public class...
I'm getting an error for this code? it won't compile import java.util.*; import java.io.*; public class Qup3 implements xxxxxlist {// implements interface    // xxxxxlnk class variables    // head is a pointer to beginning of rlinked list    private node head;    // no. of elements in the list    // private int count; // xxxxxlnk class constructor    Qup3() {        head = null;        count = 0;    } // end Dersop3 class constructor   ...
I need a java flowchart diagram for the following code: import java.util.*; public class Main {...
I need a java flowchart diagram for the following code: import java.util.*; public class Main {    public static void main(String[] args) {    Scanner sc=new Scanner(System.in);           System.out.print("Enter the input size: ");        int n=sc.nextInt();        int arr[]=new int[n];        System.out.print("Enter the sequence: ");        for(int i=0;i<n;i++)        arr[i]=sc.nextInt();        if(isConsecutiveFour(arr))        {        System.out.print("yes the array contain consecutive number:");        for(int i=0;i<n;i++)        System.out.print(arr[i]+" ");   ...
Write the following Java code into Pseudocode import java.util.*; public class Main { // Searching module...
Write the following Java code into Pseudocode import java.util.*; public class Main { // Searching module public static void score_search(int s,int score[]) { // Initialise flag as 0 int flag=0; // Looping till the end of the array for(int j=0;j<10;j++) { // If the element is found in the array if(s==score[j]) { // Update flag to 1 flag=1; } } // In case flag is 1 element is found if(flag==1) { System.out.println("golf score found"); } // // In case flag...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution {...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); HashMap labs = new HashMap(); while (true) { System.out.println("Choose operation : "); System.out.println("1. Create a Lab"); System.out.println("2. Modify a Lab"); System.out.println("3. Delete a Lab"); System.out.println("4. Assign a pc to a Lab"); System.out.println("5. Remove a pc from a Lab"); System.out.println("6. Quit"); int choice = sc.nextInt(); String name=sc.nextLine(); switch (choice) { case 1:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT