Question

Sort by the following (name, address, dependent and gender) of these and ask the user which...

Sort by the following (name, address, dependent and gender) of these and ask the user which field to sort by !. this mean the following java must sort by address if we need, by name , by dependent , and by gender it depend on the following java it must have an option which we need to sort. please i need your help now, you just add the sorting on the following java.

// Use a custom comparator.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class Emprec {
   String name;
   String address;
   double hours;
   double rate;
   int dependents;
   char gender;
   boolean degree;

   // This is the classes's constructor !!!!

   Emprec(String name, String address, String hours,String dependents) {

       try {
           this.name = name;
           this.address = address;
           this.hours = Double.valueOf(hours).doubleValue();
           this.dependents = Integer.parseInt(dependents);
       } catch (NumberFormatException errmsg) {
           System.out.println("Invalid format" + errmsg);

           this.name = "";
           this.hours = 0.0;

       }// catch

   }// Emprec constructor !!!!

   double calc_fed_tax(double hours, double rate) {

       double yearly_income;

       yearly_income = hours * rate * 52;

       if (yearly_income < 30000.00)
           return (hours * rate * .28);

       else if (yearly_income < 50000.00)
           return (hours * rate * .32);

       else
           return (hours * rate * .38);

   }// calc_fed_tax

   double calc_state_tax(double hours, double rate) {

       double state_tax;

       state_tax = hours * rate * .0561;

       return (state_tax);

   }// calc_state_tax

   public void setName(String name) {
       this.name = name;
   }

   public String getName() {
       return name;
   }
  
   public String getAddress() {
       return address;
   }

   public double getHours() {
       return hours;
   }
  
   public int getDependents() {
       return dependents;
   }
  
public double getRate(){
return rate;
}
  
public char getGender(){
return gender;
}

   public String toString() {

       return ("\n Name: " + name +
               "\n Address: " + address +
               "\n Hours: " + hours+
               "\n Dependents " + dependents);

   }// toString
}// Emprec

public class CompDemo3Sorts_Improved {
   public static void main(String args[]) throws IOException {
       // Create a tree set
       BufferedReader inData = new BufferedReader(new InputStreamReader(
               System.in));

       // create strings for the input data for the Emprec object
       String str_name;
       String str_address;
       String str_hours;
       String str_dependents;

       TreeSet ts = new TreeSet(new MyCompHours());// eclipse ask for casting
       for (;;) {
           System.out.print(" name: ");
           str_name = inData.readLine();

           if (str_name.equalsIgnoreCase("exit")) break;
          
           System.out.print(" Address: ");
           str_address = inData.readLine();
          
           System.out.print(" Hours: ");
           str_hours = inData.readLine();
          
               System.out.print(" Dependents: ");
           str_dependents = inData.readLine();

           Emprec employee = new Emprec(str_name, str_address, str_hours,str_dependents);

           ts.add(employee);
       }// for

       // Get an iterator
       Iterator i = ts.iterator();

       // Display elements
       while (i.hasNext()) {
           Object element = i.next();
           System.out.print(element + "\n");// calls the toString()
       }//while
       System.out.println();
   }
}

class MyCompName implements Comparator{ // eclipse ask for casting object
   public int compare(Object emp1, Object emp2) {

       String emp1Name = ((Emprec) emp1).getName();

       String emp2Name = ((Emprec) emp2).getName();

       return ((emp2Name.compareTo(emp1Name) <= 0) ? -1 : +1);
      
   }
}


class MyCompHours implements Comparator{ // eclipse ask for casting object
   public int compare(Object emp1, Object emp2) {

       double emp1Hours = ((Emprec) emp1).getHours();

       double emp2Hours = ((Emprec) emp2).getHours();

      
       return (emp1Hours <= emp2Hours)? -1:+1;
   }
}


class MyCompAddress implements Comparator{ // eclipse ask for casting object
   public int compare(Object emp1, Object emp2) {

       String emp1Address = ((Emprec) emp1).getAddress();

       String emp2Address = ((Emprec) emp2).getAddress();

      
       return ((emp2Address.compareTo(emp1Address) <= 0) ? -1 : +1);
      
   }
}


class MyCompRate implements Comparator{
public int compare(Object emp1, Object emp2){
double emp1Rate = ((Emprec) emp1).getRate();
double emp2Rate = ((Emprec) emp2).getRate();
      
return ((emp1Rate <= emp2Rate) ? -1 : +1);
}
}


class MyCompDependents implements Comparator{
public int compare(Object emp1, Object emp2){
int emp1Dependents = ((Emprec) emp1).getDependents();
int emp2Dependents = ((Emprec) emp2).getDependents();
      
return ((emp1Dependents <= emp2Dependents) ? -1 : +1);
}
}


class MyCompGender implements Comparator{
public int compare(Object emp1, Object emp2){
char emp1Gender = ((Emprec) emp1).getGender();
char emp2Gender = ((Emprec) emp2).getGender();
      
return ((emp1Gender <= emp2Gender) ? -1 : +1);
}
}

Homework Answers

Answer #1

Program Plan:

  • Class Emprec constructor is modified to have an input parameter gender instead of hours.
  • Class CompDemo3Sorts_Improved is modified to have 2 more local variables "choice and sortBy".
  • The variable "ts" datatype is changed from TreeSet to ArrayList.
  • For loop is replaced with do-while to allow user to exit after adding few records based on user choice.
  • Print options available for user to select sorting option.
  • Based on user input sort the list and display the objects.
  • Name and Address Comparator classes are modified to get correct sorting order similar to other comparator classes.
  • Screenshot of Sample input and output is added for reference.

Program:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


class Emprec {
   String name;
   String address;
   double hours;
   double rate;
   int dependents;
   char gender;
   boolean degree;

   // Emprec Constructor
   Emprec(String name, String address, String gender, String dependents) {
       try {
           this.name = name;
           this.address = address;
           this.gender = gender.charAt(0);


           this.dependents = Integer.parseInt(dependents);
       } catch (NumberFormatException errmsg) {
           System.out.println("Invalid format" + errmsg);
           this.name = "";
           this.hours = 0.0;
       } // catch

   }// Emprec constructor !!!!

   double calc_fed_tax(double hours, double rate) {
       double yearly_income;
       yearly_income = hours * rate * 52;

       if (yearly_income < 30000.00)
           return (hours * rate * .28);
       else if (yearly_income < 50000.00)
           return (hours * rate * .32);
       else
           return (hours * rate * .38);
   }// calc_fed_tax

   double calc_state_tax(double hours, double rate) {
       double state_tax;
       state_tax = hours * rate * .0561;
       return (state_tax);
   }// calc_state_tax


   public void setName(String name) {
       this.name = name;
   }

   public String getName() {
       return name;
   }

   public String getAddress() {
       return address;
   }

   public double getHours() {
       return hours;
   }

   public int getDependents() {
       return dependents;
   }

   public double getRate() {
       return rate;
   }

   public char getGender() {
       return gender;
   }

   public String toString() {
       return ("{ Name: " + name + ", Address: " + address + ", Gender: " + gender + ", Dependents " + dependents
               + "}");
   }// toString
}// Emprec


public class CompDemo3Sorts_Improved {
   @SuppressWarnings("unchecked")
   public static void main(String args[]) throws IOException {
       // Create a tree set
       BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));


       // create strings for the input data for the Emprec object
       String str_name;
       String str_address;
       String str_gender;
       String str_dependents;

       String choice;
       int sortBy;
       ArrayList<Emprec> ts = new ArrayList<>();// Array list for Emprec


       do {
           System.out.print(" name: ");
           str_name = inData.readLine();

           System.out.print(" Address: ");
           str_address = inData.readLine();
           // get gender
           System.out.print(" Gender: ");
           str_gender = inData.readLine();

           System.out.print(" Dependents: ");
           str_dependents = inData.readLine();

           Emprec employee = new Emprec(str_name, str_address, str_gender, str_dependents);

           ts.add(employee);
           System.out.println("Press Y to add another employee record or N to exit : ");
           choice = inData.readLine();// get user input to add employee record
       } while (choice.equalsIgnoreCase("Y"));

       System.out.println("*************************************************************");
       System.out.println("\t\t\tList Before Sorting ");
       System.out.println("*************************************************************");
       // print unsorted list
       ts.forEach(System.out::println);


       // Sorting selection by user
       System.out.println("Sorting selection : ");
       System.out.println("Press 1 to sort by Name");
       System.out.println("Press 2 to sort by Address");
       System.out.println("Press 3 to sort by Dependent ");
       System.out.println("Press 4 to sort by Gender");

       sortBy = Integer.parseInt(inData.readLine());// get user input

       if (sortBy == 1)
           Collections.sort(ts, new MyCompName());// sort by name
       else if (sortBy == 2)
           Collections.sort(ts, new MyCompAddress());// sort by address
       else if (sortBy == 3)
           Collections.sort(ts, new MyCompDependents());// sort by dependents
       else
           Collections.sort(ts, new MyCompGender());// sort by gender

       System.out.println("*************************************************************");
       System.out.println("\t\t\tList After Sorting ");
       System.out.println("*************************************************************");
       // print sorted list
       ts.forEach(System.out::println);
   }
}


//Name Comparator Class
class MyCompName implements Comparator { // eclipse ask for casting object
   public int compare(Object emp1, Object emp2) {

       String emp1Name = ((Emprec) emp1).getName();

       String emp2Name = ((Emprec) emp2).getName();


       return (emp1Name.compareTo(emp2Name));

   }
}


//Hours Comparator Class
class MyCompHours implements Comparator { // eclipse ask for casting object
   public int compare(Object emp1, Object emp2) {

       double emp1Hours = ((Emprec) emp1).getHours();

       double emp2Hours = ((Emprec) emp2).getHours();

       return (emp1Hours <= emp2Hours) ? -1 : 1;
   }
}

//Address Comparator Class
class MyCompAddress implements Comparator { // eclipse ask for casting object
   public int compare(Object emp1, Object emp2) {

       String emp1Address = ((Emprec) emp1).getAddress();

       String emp2Address = ((Emprec) emp2).getAddress();

       return (emp1Address.compareTo(emp2Address));


   }
}

//Rate Comparator Class
class MyCompRate implements Comparator {
   public int compare(Object emp1, Object emp2) {
       double emp1Rate = ((Emprec) emp1).getRate();
       double emp2Rate = ((Emprec) emp2).getRate();

       return ((emp1Rate <= emp2Rate) ? -1 : 1);
   }
}

//Dependents Comparator Class
class MyCompDependents implements Comparator {
   public int compare(Object emp1, Object emp2) {
       int emp1Dependents = ((Emprec) emp1).getDependents();
       int emp2Dependents = ((Emprec) emp2).getDependents();
       return ((emp1Dependents <= emp2Dependents) ? -1 : 1);
   }
}

//Gender Comparator Class
class MyCompGender implements Comparator {
   public int compare(Object emp1, Object emp2) {
       char emp1Gender = ((Emprec) emp1).getGender();
       char emp2Gender = ((Emprec) emp2).getGender();
       return ((emp1Gender <= emp2Gender) ? -1 : +1);
   }
}

Sample Input and Output:

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
What's wrong with this code? #Java Why I am getting error in : int BusCompare =...
What's wrong with this code? #Java Why I am getting error in : int BusCompare = o1.numberOfBusinesses.compareTo(o2.numberOfBusinesses); public class TypeComparator implements Comparator<Type> { @Override public int compare(Type o1, Type o2) { // return o1.name.compareTo(o2.name); int NameCompare = o1.name.compareTo(o2.name); int BusCompare = o1.numberOfBusinesses.compareTo(o2.numberOfBusinesses); // 2-level comparison using if-else block if (NameCompare == 0) { return ((BusCompare == 0) ? NameCompare : BusCompare); } else { return NameCompare; } } } public class Type implements Comparable<Type> { int id; String name; int...
Write a pseudocode for the following java programs: public class Item {    private String name;...
Write a pseudocode for the following java programs: public class Item {    private String name;    private double cost;    public Item(String name, double cost) {        this.name = name;        this.cost = cost;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public double getCost() {        return cost;    }    public void setCost(double cost) {...
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
Provide A UML for the Following CODE public class Employee{ public String strName, strSalary; public Employee(){...
Provide A UML for the Following CODE public class Employee{ public String strName, strSalary; public Employee(){    strName = " ";    strSalary = "$0";    } public Employee(String Name, String Salary){    strName = Name;    strSalary = Salary;    } public void setName(String Name){    strName = Name;    } public void setSalary(String Salary){    strSalary = Salary;    } public String getName(){    return strName;    } public String getSalary(){    return strSalary;    } public String...
Determine how all of your classes are related, and create a complete UML class diagram representing...
Determine how all of your classes are related, and create a complete UML class diagram representing your class structure. Don't forget to include the appropriate relationships between the classes. GameDriver import java.util.Scanner; public class GameDriver { Scanner in = new Scanner(System.in); public static void main(String[] args) { Move move1 = new Move("Vine Whip", "Grass", 45, 1.0f); Move move2 = new Move("Tackle", "Normal", 50, 1.0f); Move move3 = new Move("Take Down", "Normal", 90, 0.85f); Move move4 = new Move("Razor Leaf", "Grass",...
How do I get this portion of my List Iterator code to work? This is a...
How do I get this portion of my List Iterator code to work? This is a portion of the code in the AddressBookApp that I need to work. Currently it stops at Person not found and if it makes it to the else it gives me this Exception in thread "main" java.lang.NullPointerException    at AddressBookApp.main(AddressBookApp.java:36) iter.reset(); Person findPerson = iter.findLastname("Duck"); if (findPerson == null) System.out.println("Person not found."); else findPerson.displayEntry(); findPerson = iter.findLastname("Duck"); if (findPerson == null) { System.out.println("Person not found.");...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list code and can't figure out how to complete it: Below is the code Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. /////////////////////////////////////////////////////////////////////////////////////////////////////////// Grocery Class (If this helps) package Shopping; public class Grocery implements Comparable<Grocery> { private String name; private String category; private int aisle; private float price; private int quantity;...
Java : Modify the selection sort algorithm to sort an array of integers in descending order....
Java : Modify the selection sort algorithm to sort an array of integers in descending order. describe how the skills you have gained could be applied in the field. Please don't use an already answered solution from chegg. I've unfortunately had that happen at many occasion ....... ........ sec01/SelectionSortDemo.java import java.util.Arrays; /** This program demonstrates the selection sort algorithm by sorting an array that is filled with random numbers. */ public class SelectionSortDemo { public static void main(String[] args) {...
I wrote the following java code with the eclipse ide, which is supposed to report the...
I wrote the following java code with the eclipse ide, which is supposed to report the number of guesses it took to guess the right number between one and five. Can some repost the corrected code where the variable "guess" is incremented such that the correct number of guesses is displayed? please test run the code, not just look at it in case there are other bugs that exist. import java.util.*; public class GuessingGame {    public static final int...
JAVA public class Purchase { private String name; private int groupCount; //Part of price, like the...
JAVA public class Purchase { private String name; private int groupCount; //Part of price, like the 2 in 2 for $1.99. private double groupPrice; //Part of price, like the $1.99 in 2 for $1.99. private int numberBought; //Total number being purchased. public Purchase () { name = "no name"; groupCount = 0; groupPrice = 0; numberBought = 0; } public Purchase (String name, int groupCount, double groupPrice, int numberBought) { this.name = name; this.groupCount = groupCount; this.groupPrice = groupPrice; this.numberBought...