Java Reference
In-Depth Information
credits. You might find that your program is more useful with a private setAmount() method only
for use in the constructor and other public withdraw() and deposit() methods to add or subtract
funds from the amount. Inside the methods, you can check for negative balances to make sure the
account is not overdrawn. Add these three methods to your Account class.
private void setAmount(String newAmount){
this.amount = new BigDecimal(newAmount);
}
 
public void withdraw(String withdrawal) throws IllegalArgumentException{
BigDecimal desiredAmount = new BigDecimal(withdrawal);
 
//if desired amount is negative, throw an exception
if (desiredAmount.compareTo(BigDecimal.ZERO) < 0){
throw new IllegalArgumentException();
}
 
//if the amount is less than the desired amount, throw an exception
if (amount.compareTo(desiredAmount) < 0){
throw new IllegalArgumentException();
}
 
this.amount = this.amount.subtract(desiredAmount);
}
 
public void deposit(String deposit) throws IllegalArgumentException{
BigDecimal desiredAmount = new BigDecimal(deposit);
 
//if desired amount is negative, throw an exception
if (desiredAmount.compareTo(BigDecimal.ZER0) < 0){
throw new IllegalArgumentException();
}
 
this.amount = this.amount.add(desiredAmount);
}
15. Once your setters are in place, rewrite your constructor to use them.
public Account(String acctName, String startAmount) {
setName(acctName);
setAmount(startAmount);
amount.setScale(2, BigDecimal.ROUND_HALF_UP);
}
16. Your complete Account class should look like this:
import java.math.BigDecimal;
 
public class Account {
private String name;
private BigDecimal amount;
 
public Account(String acctName, String startAmount) {
Search WWH ::




Custom Search