Skip to content

Commit 5e1a52e

Browse files
Merge pull request #29 from code4tomorrow/fix-bank
Update Bank.java
2 parents 1bc9537 + 0a10fce commit 5e1a52e

File tree

1 file changed

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

1 file changed

+15
-14
lines changed

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

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,43 +34,44 @@ 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(String.format("Bank balance is short $%.2f", Math.abs(balance - amount)));
70+
}
7071
balance -= amount;
7172
}
7273

73-
public int getBalance() {
74+
public double getBalance() {
7475
return balance;
7576
}
7677
}

0 commit comments

Comments
 (0)