Well, first off, the problem states that our method should accept a second BankAccount, not a String. So, our method header will look like:
public void transfer(BankAccount other, double amount)
I think this was the main thing you were stuck with -- getting the correct type signature. Apart from that, it looks like you were on the right track.
Then, we can get to the business of writing the code. If the balance in the current bank account is too small, we'll just terminate early:
if (balance - 5.0 <= 0) {
return;
}
...or if you prefer, we can write this as:
if (this.balance - 5.0 <= 0) {
return;
}
...to make it absolutely clear that we're distinguishing between this.balance and other.balance.
Then, we'll need to handle the two cases where there's not enough money to transfer, and the normal case. We'll also need to update the transactions.
if (this.balance - 5.0 - amount <= 0) {
double transferred = this.balance - 5.0;
other.balance += transferred;
this.balance = 0;
} else {
this.balance - 5.0 - amount;
other.balance += amount;
}
this.transations++;
other.transactions++;
Putting it all together:
public void transfer(BankAccount other, double amount) {
if (this.balance - 5.0 <= 0) {
return;
} else {
if (this.balance - 5.0 - amount <= 0) {
double transferred = this.balance - 5.0;
other.balance += transferred;
this.balance = 0;
} else {
this.balance - 5.0 - amount;
other.balance += amount;
}
this.transactions++;
other.transactions++;
}
}
...or more concisely,
public void transfer(BankAccount other, double amount) {
if (this.balance - 5.0 > 0) {
if (this.balance - 5.0 - amount <= 0) {
double transferred = this.balance - 5.0;
other.balance += transferred;
this.balance = 0;
} else {
this.balance - 5.0 - amount;
other.balance += amount;
}
this.transactions++;
other.transactions++;
}
}
Normally, I wouldn't use the this
keyword so frequently, since it usually doesn't add much, but here, it adds an interesting symmetry that exposes how this
and other
are really two different BankAccount objects.
We can modify this.balance
in the same way we can other.balance
, and it's sort of aesthetically pleasing how they mirror each other, in a way.
We could also use the deposit
method (and it's probably preferable to do so), but I didn't see that method until I finished writing this email, and am too lazy to go back and change all my code samples.