我寫了一個小作業(yè),其中創(chuàng)建了一個TimeDepositAccount方法,并正在創(chuàng)建一個方法來獲取當前余額,計算利息后的新余額,然后創(chuàng)建一個提款方法。我一直堅持打印新余額,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條經(jīng)驗 獲得超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
提交
取消