简体   繁体   English

如何打印第一个余额,然后是新的余额?

[英]How can I print the first balance, then the new balance?

I've written a small assignment where I've created a TimeDepositAccount and am creating a method to get the current balance, new balance after calculating the interest, and then a withdraw method.我写了一个小作业,我创建了一个TimeDepositAccount并创建了一个方法来获取当前余额,计算利息后的新余额,然后是一个提取方法。 I'm stuck on printing the new balance to System.out since for some reason, I'm unable to get the new balance.我一直坚持将新余额打印到System.out ,因为由于某种原因,我无法获得新余额。 Second, I want to use a local variable for the withdraw method since in our upcoming test we'll be tested on those, but we never did them in class so I'm unsure as how to go about that.其次,我想为提取方法使用局部变量,因为在我们即将进行的测试中,我们将对其进行测试,但我们从未在 class 中做过它们,所以我不确定如何使用 go。

    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);

    }
}

I wanted the output to first print 10.0, then 10.2, but instead I get 10.0 both times.我希望 output 先打印 10.0,然后打印 10.2,但我两次都得到 10.0。

You would want to change your main method to the following:您可能希望将 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);
}

The variable currentBalance stores what the balance was when you defined it.变量currentBalance存储定义时的余额。 Changing the balance of tda does not change the value of currentBalance .更改tda的余额不会更改currentBalance的值。 Thus, to update the value of currentBalance , you need to run currentBalance = tda.getcurrentBalance();因此,要更新currentBalance的值,您需要运行currentBalance = tda.getcurrentBalance(); again.再次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM