Question

In: Computer Science

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) {

        return false;

    }

    /**

     * TO DO: override hashCode here

     */

    @Override

    public int hashCode() {

        return 0;

    }

    /**

     * TO DO:

     * Write compareTo (natural ordering of class):

     * 1. accountNumber in ascending order

     *      If same, break ties:

     * 2. old Accounts before new accounts

     *      If same, break ties

     * 3. LastName

     *      If same, break ties

     * 4. FirstName

     *      If same, break ties

     * 5. Lower Balance before higher balance

     */

    @Override

    public int compareTo(Account other) {

        final int BEFORE = -1;

        final int EQUAL = 0;

        final int AFTER = 1;

        return EQUAL;

    }

}

===========================

import java.util.Comparator;

/*

* TO DO:

*This class should compare all accounts by balance only (in ascending order)

*/

Solutions

Expert Solution

The updated code for Account.java class is as below:

import java.util.*;

public final class Account implements Comparable<Account> {
        
    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;
    }

    
    public String getFirstName() {
                return firstName;
        }


        public String getLastName() {
                return lastName;
        }


        public int getAccountNumber() {
                return accountNumber;
        }


        public double getBalance() {
                return balance;
        }


        public boolean isNewAccount() {
                return isNewAccount;
        }


        public void setFirstName(String firstName) {
                this.firstName = firstName;
        }


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


        public void setAccountNumber(int accountNumber) {
                this.accountNumber = accountNumber;
        }


        public void setBalance(double balance) {
                this.balance = balance;
        }


        public void setNewAccount(boolean isNewAccount) {
                this.isNewAccount = isNewAccount;
        }
        
        /**

     * TO DO: override equals

     */

    @Override

    public boolean equals(Object other) {

        return false;

    }

    /**

     * TO DO: override hashCode here

     */

    @Override

    public int hashCode() {

        return 0;

    }

    /**

     * TO DO:

     * Write compareTo (natural ordering of class):

     * 1. accountNumber in ascending order

     *      If same, break ties:

     * 2. old Accounts before new accounts

     *      If same, break ties

     * 3. LastName

     *      If same, break ties

     * 4. FirstName

     *      If same, break ties

     * 5. Lower Balance before higher balance

     */

        @Override
        public int compareTo(Account other) {            
                 return Comparator.comparingInt(Account::getAccountNumber)
                         .thenComparing(Account::isNewAccount)
                         .thenComparing(Account::getLastName)
                         .thenComparing(Account::getFirstName)
                         .thenComparingDouble(Account::getBalance)
                         .compare(this, other);          
        }
        
        
        public String toString() {
                String str;
                if(isNewAccount)
                        str = "is new account";
                else
                        str = "is not a new account";
                return accountNumber+" "+str+" with name "+firstName+" "+lastName+" with a balance of "+ balance;
        }
}

The class used to compare any 2 Account class objects as below:

import java.util.Comparator;

public class AccountComparing  implements Comparator<Account>{

        @Override
        public int compare(Account ac1, Account ac2) {
                return ac1.compareTo(ac2);
        }
}

I have tested the above functionality using another class as below:

import java.util.Arrays;

public class Testing {
        public static void main(String[] args){
                Account ac[] = new Account[4];
                ac[0] = new Account("John", "valles", 10, 70000, true);
                ac[1] = new Account("Angel", "Lopez", 11, 8000, false);
                ac[2] = new Account("Angel", "Arun", 11, 900, true);    
                ac[3] = new Account("Angel", "Arun", 11, 700, true);
                Arrays.sort(ac);
                
                for(Account a : ac){
                        System.out.println(a.toString());
                }
                
        }
}

The ouput screenshot of the above program is :

If you have any queries reagrding this answer, please reach out through the comment section.


Related Solutions

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...
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   ...
*// 1- Add JavaDoc to This classes 2- Mak a UML */ import java.util.*; public class...
*// 1- Add JavaDoc to This classes 2- Mak a UML */ import java.util.*; public class Display { public static void main(String[] args) { altEnerCar car1 = new altEnerCar(20000, 2001, 20000); altEnerCar car2 = new HydrogenCar(0, 2012, 50000, 100, false); altEnerCar car3 = new ElectricCar(0, 2014, 30000, 10, 50); altEnerCar car4 = new NaturalGasCar(0, 2000, 60000, 5, 20); altEnerCar car5 = new PropaneCar(0, 2011, 45000, 10, true); ArrayList<altEnerCar> cars = new ArrayList<altEnerCar>(); cars.add(car1); cars.add(car2); cars.add(car3); cars.add(car4); cars.add(car5); Collections.sort(cars); System.out.println(cars); }...
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:...
import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void...
import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void main(String[] args) throws Exception { Crypto crypto = new BasicCrypto();        String welcome = "Hello 2043-er's! Let's try this again :-)"; System.out.println(welcome); // First, where are we? //Let's print out our current working directory        Path cwd = FileSystems.getDefault().getPath("").toAbsolutePath(); System.out.println("Current Working Directory: " + cwd); // Read in our file to encrypt    byte[] originalData = Files.readAllBytes(Paths.get(System.getProperty("user.home"), "C-2044-Sample/Crypto/src/encrypt.txt")); // Encrypt it and...
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 CODE FROM JAVA TO C# PLEASE AND SHOW OUTPUT import java.util.*; public class TestPaperFolds {...
CONVERT CODE FROM JAVA TO C# PLEASE AND SHOW OUTPUT import java.util.*; public class TestPaperFolds {    public static void main(String[] args)    {        for(int i = 1; i <= 4; i++)               //loop for i = 1 to 4 folds        {            String fold_string = paperFold(i);   //call paperFold to get the String for i folds            System.out.println("For " + i + " folds we get: " + fold_string);        }    }    public static String paperFold(int numOfFolds)  ...
Explain the java class below, how it make: import java.util.*; import java.util.concurrent.TimeUnit; public class RacingGame {...
Explain the java class below, how it make: import java.util.*; import java.util.concurrent.TimeUnit; public class RacingGame {       ArrayList<Driver> player = new ArrayList<Driver>();    CarType car = new CarType("Ferrari","2018",280,90,15);    Formula formula = new Formula(5);// number of laps    long startTime = System.currentTimeMillis();    long currentTime = System.currentTimeMillis();    int totalDis = 0;       public static void main(String[] args)    {        RacingGame formulaRace = new RacingGame();        formulaRace.player.add(new Driver("Saleh",10,3));        formulaRace.formula.setDistance(20);//lap distance        formulaRace.totalDis...
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;   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT