java - 我的 Java 程序中没有更新余额
问题描述
我编写了一个 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
解决方案
你从来没有interestRate
在你的SavingsAccount
构造函数中设置。由于存款乘以那个(它是零)它永远不会更新。
public SavingsAccount(int accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
this.interestRate = interestRate;
}
此外,利息可能不应该在存款中支付。
public void deposit(double amount) {
balance += amount;
}
推荐阅读
- python - 我想在 python 中从用户那里获取多行输入
- java - 带有 Keycloak 和 Play 框架的 SocketTimeoutException
- python - 正则表达式匹配尽可能少的字符
- excel - Excel公式返回与搜索字符串对应的所有行和列
- python - 将字典转换为 JSON 字符串,并将“None”值保存为“None”而不是“null”
- jquery - 我正在尝试使用 jquery 启用/禁用与输入值相关的输入字段
- python - 如何在 Python 中将多个 csv 文件放入一个 sqlite 或 mysql 数据库中?
- angular - 如何测试正确的数据是否传递给投影(ng-content)?
- docker - 由于访问权限,Windows 的 Docker 无法编辑来宾中的文件
- javascript - 错误:连接到本地主机上的任何内容时连接 ECONNREFUSED 127.0.0.1