我写了一个小作业,其中创建了一个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。
1 回答

慕虎7371278
TA贡献1802条经验 获得超4个赞
您需要将 main 方法更改为以下内容:
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();再次运行。
添加回答
举报
0/150
提交
取消