我应该使用抽象方法BankAcct
设计一个computeIntt()
类。 Save和Time是BankAcct的种类。问题是我无法实现兴趣和新余额的显示
这是我目前的代码:
public abstract class BankAcct
{
private int accountNumber;
private String accountName;
private double bal;
public BankAcct(int act, String name, double m)
{
accountNumber = act;
accountName = name;
bal = m;
}
public double getBalance()
{
return bal;
}
public String getAccountName()
{
return accountName;
}
public int getAccountNumber()
{
return accountNumber;
}
public void deposit(double m)
{
bal+=m;
}
public void withdraw(double m)
{
bal-=m;
}
public abstract double computeInt();
}
public class Save extends BankAcct
{
public Save(int act, String name, double m)
{
super(act, name, m);
}
int act;
String name="";
double m;
public double computeInt()
{
return m * 0.0025;
}
}
public class Time extends BankAcct
{
public Time(int act, String name, double m)
{
super(act, name, m);
}
int act;
String name="";
double m;
public double computeInt()
{
return m * 0.033;
}
}
public class MainPr
{
public static void main(String[] args)
{
BankAcct sav = new Savings(1234, "ABC", 10000);
BankAcct td = new TimeDeposit(9876, "DEF", 20000);
// display the current balance
System.out.println(sav.getAccountName() + " with account number " +
sav.getAccountNumber() + " has a balance of " +
sav.getBalance());
System.out.println(td.getAccountName() + " with account number " +
td.getAccountNumber() + " has a balance of " +
td.getBalance());
// deposit money
sav.withdraw(5000.0);
// display current value with its interest
System.out.println("\n" + sav.getAccountName() + " with account number " +
sav.getAccountNumber() + " earned an interest of " +
sav.computeInt());
System.out.println(sav.getAccountName() + " with account number " +
sav.getAccountNumber() + " has a NEW BALANCE of " +
sav.getBalance());
td.deposit(2000.0);
System.out.println("\n" + td.getAccountName() + " with account number " +
td.getAccountNumber() + " earned an interest of " +
td.computeInt());
System.out.println(td.getAccountName() + " with account number " +
td.getAccountNumber() + " has a NEW BALANCE of " +
td.getBalance());
}
}
MainPr将为以下数据实例化两个对象: 保存帐号为1234; ABC的帐户名称;余额10,000。 时间账号为9876;帐户名称DEF;余额20,000。
这应该是输出:CORRECT ONE
帐号为1234的ABC余额为10000.0
帐号为9876的DEF余额为20000.0
账号为1234的ABC赚取利息25.0
账号为1234的ABC新余额为5025.0
帐号为9876的DEF赚取利息660.0
帐号为9876的DEF的余额为22660.0
但我的程序产生错误的输出:
帐号为1234的ABC余额为10000.0
帐号为9876的DEF余额为20000.0
账号为1234的ABC赚取利息0.0
账号为1234的ABC新余额为5000.0
帐号为9876的DEF赚取利息0.0
帐号为9876的DEF的余额为22000.0
在这种情况下,保存利率为0.25%,而利息时间为3.3%。余额取决于存款或取款。
请帮助我。感谢
答案 0 :(得分:1)
您的实例变量m
在您的子类中始终为0
(从未初始化),但它们看起来设置为bal
类中的BankAcct
。这不适合computerInterest
中的TimeDeposit
方法:
public double computeInterest() {
return getBalance() * 0.033;
}
应在其他子类中提供类似的修补程序,或者至少初始化m
个变量。在相关的说明中,您的子类不需要定义act
或name
,因为您的超类BankAcct
已经定义并存储了它。
此外,您的computerInterest
并未修改您的计划似乎期望的余额。如果是这种情况,这可能更合适:
public double computeInterest() {
double interest = getBalance() * 0.033;
deposit(interest);
return interest;
}