Skip to content

Commit 9b87e2f

Browse files
committed
Update Bank.java
- Add string formatting to print money values in standard form - Change monetary parameters to `double`s instead of `int`s - Remove unused `diff` variable in `Bank.withdraw()` - Use `getMessage()` instead of `toString()` for handling `NotEnoughMoneyException` to avoid printing full exception name - Update `deposit` method to account for negative `amount`s
1 parent 1a9bd2f commit 9b87e2f

File tree

1 file changed

+17
-14
lines changed
  • src/com/codefortomorrow/advanced/chapter14/solutions

1 file changed

+17
-14
lines changed

src/com/codefortomorrow/advanced/chapter14/solutions/Bank.java

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,43 +34,46 @@ public static void main(String[] args) {
3434

3535
account1.deposit(200);
3636
withdraw(account1, 300);
37-
System.out.println("Account 1: " + account1.getBalance());
37+
System.out.printf("Account 1 Balance: $%.2f\n", account1.getBalance());
3838

3939
account2.deposit(200);
4040
withdraw(account2, 1500);
41-
System.out.println("Account 2: " + account2.getBalance());
41+
System.out.printf("Account 2 Balance: $%.2f\n", account2.getBalance());
4242
}
4343

44-
public static void withdraw(BankAccount account, int amount) {
44+
public static void withdraw(BankAccount account, double amount) {
4545
try {
4646
account.withdraw(amount);
4747
} catch (NotEnoughMoneyException e) {
48-
int diff = Math.abs(amount - account.getBalance());
49-
System.out.println(e.toString());
48+
System.out.println(e.getMessage());
5049
}
5150
}
5251
}
5352

5453
class BankAccount {
5554

56-
private int balance;
55+
private double balance;
5756

58-
public BankAccount(int balance) {
57+
public BankAccount(double balance) {
5958
this.balance = balance;
6059
}
6160

62-
public void deposit(int amount) {
63-
balance += amount;
61+
public void deposit(double amount) {
62+
if (amount > 0) {
63+
balance += amount;
64+
}
6465
}
6566

66-
public void withdraw(int amount) throws NotEnoughMoneyException {
67-
if (amount > balance) throw new NotEnoughMoneyException(
68-
"Bank balance is short $" + Math.abs(balance - amount)
69-
);
67+
public void withdraw(double amount) throws NotEnoughMoneyException {
68+
if (amount > balance) {
69+
throw new NotEnoughMoneyException(
70+
String.format("Bank balance is short $%.2f", Math.abs(balance - amount))
71+
);
72+
}
7073
balance -= amount;
7174
}
7275

73-
public int getBalance() {
76+
public double getBalance() {
7477
return balance;
7578
}
7679
}

0 commit comments

Comments
 (0)