当我尝试提取超过透支限额的金额时,就会出现问题。在这个例子中,第二次提款后的余额不应低于允许的透支限额,但事实却是这样。
如何修改
CheckingAccount
类中的提现方法,防止提现超出透支限额?
interface Account {
void deposit(double amount);
void withdraw(double amount);
double getBalance();
}
abstract class BankAccount implements Account {
protected double balance;
protected String accountNumber;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
@Override
public double getBalance() {
return balance;
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
public SavingsAccount(String accountNumber, double initialBalance, double interestRate) {
super(accountNumber, initialBalance);
this.interestRate = interestRate;
}
public void addInterest() {
balance += balance * interestRate;
}
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
}
class CheckingAccount extends BankAccount {
private double overdraftLimit;
public CheckingAccount(String accountNumber, double initialBalance, double overdraftLimit) {
super(accountNumber, initialBalance);
this.overdraftLimit = overdraftLimit;
}
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance + overdraftLimit) {
balance -= amount;
}
}
}
public class Bank {
public static void main(String[] args) {
SavingsAccount savings = new SavingsAccount("SA123", 1000, 0.05);
CheckingAccount checking = new CheckingAccount("CA123", 500, 200);
savings.deposit(200);
savings.addInterest();
System.out.println("Savings Account Balance: " + savings.getBalance());
checking.withdraw(600);
System.out.println("Checking Account Balance: " + checking.getBalance());
// Attempt to withdraw more than allowed overdraft limit
checking.withdraw(200);
System.out.println("Checking Account Balance after overdraft: " + checking.getBalance());
}
}
您可以尝试这个解决方案:
public void withdraw(double amount) {
if (amount > 0 && amount <= balance + overdraftLimit) {
if (amount <= balance) {
balance -= amount;
} else {
// Calculate how much can be withdrawn within the overdraft limit
double availableBalance = balance + overdraftLimit;
balance = 0; // Account balance becomes zero after using overdraft
System.out.println("Withdrawal exceeds balance. Using overdraft.");
System.out.println("Overdraft used: " + (amount - balance));
}
} else {
System.out.println("Withdrawal amount exceeds available balance and overdraft limit.");
}
}