import java.text.DecimalFormat; /**** * * This is a version of the BankAccount class fixes the problem with the * previous version that didn't allow AssetManager.sort to compile. This * version has exactly two differences with the previous version: * * (1) implements Compareable instead of Comparable * (2) changes the implementation of compareTo * * See lecture notes Week 5 for some discussion. * */ public class BankAccount implements Comparable, Valuable { /** The current balance of this bank account. */ private double balance; /** Name of the banking institution for this account. */ private String institution; /** * Construct a bank account with a zero balance. */ public BankAccount() { balance = 0; } /** * Construct a bank account at the given institution, with the given * initial balance. */ public BankAccount(String institution, double balance) { this.balance = balance; this.institution = institution; } /** * Deposit the given amount of money into this bank account. */ public void deposit(double amount) { if (amount < 0) { throw new IllegalArgumentException(); } balance = balance + amount; } /** * Withdraw the given amount of money from this bank account. */ public void withdraw(double amount) { if ((balance - amount < 0) || (amount < 0)) { throw new IllegalArgumentException(); } balance = balance - amount; } /** * Get the current balance of this bank account. */ public double getBalance() { return balance; } /** * Transfer the given amount from this account to the given other account. */ public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } /** * Return the string representation of this account in the form * * institution: $balance * * where the balance value is rounded to two decimal places. */ public String toString() { return institution + ": $" + new DecimalFormat(".##").format(balance); } /** * Compare this account with the given other account, using balance as the * basis of comparison. * * NOTE: Look closely at this implementation of compare */ public int compareTo(Valuable other) { if (getValue() < other.getValue()) return -1; if (getValue() == other.getValue()) return 0; return 1; } /** * Return the value of this account as its balance. * @return the value of balance */ public double getValue() { return balance; } }