首页 > 解决方案 > 如何打印第一个余额,然后是新的余额?

问题描述

我写了一个小作业,我创建了一个TimeDepositAccount并正在创建一个方法来获取当前余额,计算利息后的新余额,然后是一个取款方法。我一直坚持打印新余额,System.out因为由于某种原因,我无法获得新余额。其次,我想为withdraw方法使用一个局部变量,因为在我们即将进行的测试中,我们将对其进行测试,但我们从未在课堂上做过它们,所以我不确定如何去做。

    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。

标签: java

解决方案


您可能希望将 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();再次运行。


推荐阅读