Java 编译错误:无法找到符号 - accumulateInterestRate() 方法
Java 编译错误:无法找到符号 - accumulateInterestRate() 方法
您在代码中遇到了以下编译错误:
src/step2/TestBanking.java:34: error: cannot find symbol
sa.accumulateInterestRate();
^
symbol: method accumulateInterestRate()
location: variable sa of type SavingsAccount
该错误表明您试图在 SavingsAccount 对象 sa 上调用一个名为 accumulateInterestRate() 的方法,但该方法不存在于 SavingsAccount 类中。
解决方案:
您需要在 SavingsAccount 类中添加一个名为 accumulateInterest() 的方法来计算利息。该方法应该根据账户的余额和利率计算出应计的利息,并将利息添加到账户的余额中。
示例代码:
public class SavingsAccount extends Account {
// ... 其他成员变量和方法
public void accumulateInterest() {
double interest = getBalance() * getInterestRate();
deposit(interest);
}
}
修改后的 TestBanking.java 代码:
package step2;
import step1.OverdraftException;
import java.util.Scanner;
public class TestBanking {
public static void main(String[] args) {
// 数据的输入
Scanner sc = new Scanner(System.in);
double wamount = sc.nextDouble();
// 数据的初始化:客户+账户
Bank.addCustomer("Zhang", "san");
Customer cus1 = Bank.getCustomer(0);
cus1.addAccount(new SavingsAccount(5000, 0.017));
cus1.addAccount(new CheckingAccount(3000, 2000));
Bank.addCustomer("Li", "si");
Customer cus2 = Bank.getCustomer(1);
cus2.addAccount(new CheckingAccount(2000, 5000));
for (int i = 0; i < Bank.getNumberOfCustomers(); i++) {
Customer cus = Bank.getCustomer(i);
System.out.println(cus);
for (int j = 0; j < cus.getNumberOfAccounts(); j++) {
Account acc = cus.getAccount(j);
// 请使用try-catch捕获OverdraftException
/********** Begin *********/
System.out.printf("%d: 初始余额是->%.2f\n", (j + 1), acc.getBalance());
if (acc instanceof SavingsAccount) {
SavingsAccount sa = (SavingsAccount) acc;
sa.accumulateInterest(); // 修改为调用 accumulateInterest() 方法
System.out.printf("计算利息后的余额是->%.2f\n", sa.getBalance());
} else if (acc instanceof CheckingAccount) {
CheckingAccount ca = (CheckingAccount) acc;
try {
System.out.printf("允许透支的额度是->%.2f\n", ca.getOverdraftAmount());
ca.withdraw(wamount);
System.out.printf("取款后的余额是->%.2f\n", ca.getBalance());
System.out.printf("下一次允许透支的额度是->%.2f\n", ca.getOverdraftAmount());
} catch (OverdraftException e) {
System.out.println(e.getMessage());
System.out.printf("赤字是->%.2f\n", e.getDeficit());
}
} else {
try {
acc.withdraw(wamount);
System.out.printf("取款后的余额是->%.2f\n", acc.getBalance());
} catch (OverdraftException e) {
System.out.println(e.getMessage());
System.out.println(e.getDeficit());
}
}
/********** End *********/
}
}
sc.close();
}
}
完成上述修改后,重新编译代码,您应该能够成功运行程序了。
原文地址: https://www.cveoy.top/t/topic/nQg7 著作权归作者所有。请勿转载和采集!