gpt4 book ai didi

java - 我的 Java 程序中的余额未更新

转载 作者:行者123 更新时间:2023-12-02 01:02:38 25 4
gpt4 key购买 nike

我编写了一个java程序,其中子类是BankAccountSavingsAccount是它的子类,我正在用它进行一些交易,但余额没有得到更新并仅显示 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com