我编写了一个java程序,其中子类是BankAccount
,SavingsAccount
是它的子类,我正在用它进行一些交易,但余额没有得到更新并仅显示 0.00 作为输出。
这是我的代码:
public class BankAccountTest {
public static void main(String[] args) {
SavingsAccount savingsAccount = new SavingsAccount(879101,0,0.04);
savingsAccount.deposit(500);
savingsAccount.withdraw(500);
savingsAccount.deposit(1500);
savingsAccount.deposit(500);
savingsAccount.withdraw(500);
savingsAccount.deposit(5000);
savingsAccount.deposit(500);
savingsAccount.annualCredit();
System.out.println(savingsAccount);
}
}
class BankAccount {
private int accountNumber;
protected double balance;
public BankAccount( int accountNumber, double balance)
{
this.accountNumber = accountNumber;
this.balance = balance;
}
public int getAccountNumber () {
return accountNumber;
}
public double getBalance () {
return balance;
}
public void setAccountNumber ( int accountNumber){
this.accountNumber = accountNumber;
}
public void setBalance ( double balance){
this.balance = balance;
}
public void deposit ( double amount){
balance = balance + amount;
}
public void withdraw ( double amount){
if (amount <= balance)
balance = balance - amount;
}
public String toString () {
return String.format("Account Number=%d%nBalance=%.2f%n", accountNumber, balance);
}
}
class SavingsAccount extends BankAccount{
private double interestRate;
public SavingsAccount(int accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
}
public void deposit(double amount){
balance = balance+(interestRate*amount);
}
public void withdraw(double amount) {
super.withdraw(amount);
}
public void annualCredit(){
if (balance<=1000){
balance=interestRate*balance;
}
else if(balance<=5000){
balance=2*interestRate*balance;
}
else if(balance>5000){
balance=3*interestRate*balance;
}
}
public double getInterestRate(){
return interestRate;
}
public String toString(){
System.out.println("Account= "+getAccountNumber()+"\nBalance= "+balance+"\nInterestRate= "+interestRate);
return null;
}
}
输出:
Account= 879101
Balance= 0.0
InterestRate= 0.0
null
最佳答案
您从未在 SavingsAccount
构造函数中设置 interestRate
。由于存款乘以该值(并且为零),因此它永远不会更新。
public SavingsAccount(int accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
this.interestRate = interestRate;
}
此外,存款可能不应该支付利息。
public void deposit(double amount) {
balance += amount;
}
关于java - 我的 Java 程序中的余额未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469294/