我写了一个小作业,在其中创建了TimeDepositAccount
,并且正在创建一种方法来获取当前余额,计算利息后的新余额,然后再提取一种方法。由于某些原因,我无法将新余额打印到System.out
上,因为我无法获得新余额。其次,我想对撤销方法使用局部变量,因为在我们即将进行的测试中,我们将对它们进行测试,但是我们从未在课堂上进行过测试,因此我不确定该怎么做。
public class TimeDepositAccount {
//instance fields
private double currentBalance;
private double interestRate;
//Constructors
public TimeDepositAccount(){}
public TimeDepositAccount(double Balance1, double intRate){
currentBalance = Balance1;
interestRate = intRate;
}
//Methods
public double getcurrentBalance(){
return currentBalance;
}
public void newBalance(){
currentBalance = currentBalance * (1 + (interestRate/ 100) );
}
public double getintRate(){
return interestRate;
}
public String toString(){
return "TimeDepositAccount[ currentBalance = "+getcurrentBalance()+",
interestRate = "+getintRate()+"]";
}
public class TimeDepositAccountTester{
public static void main (String[] args){
TimeDepositAccount tda = new TimeDepositAccount(10,2);
double currentBalance = tda.getcurrentBalance();
System.out.println(currentBalance);
tda.newBalance();
System.out.print(currentBalance);
}
}
我希望输出先打印10.0,然后再打印10.2,但我两次都得到10.0。
答案 0 :(得分:1)
您想将主要方法更改为以下内容:
public static void main (String[] args){
TimeDepositAccount tda = new TimeDepositAccount(10,2);
double currentBalance = tda.getcurrentBalance();
System.out.println(currentBalance);
tda.newBalance();
currentBalance = tda.getcurrentBalance();
System.out.print(currentBalance);
}
变量currentBalance
存储定义时的余额。更改tda
的余额不会更改currentBalance
的值。因此,要更新currentBalance
的值,您需要再次运行currentBalance = tda.getcurrentBalance();
。