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   ...
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:...
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)  ...
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!
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT