How can I print the first balance, then the new balance?

I've written a small assignment where I've created a TimeDepositAccountand am creating a method to get the current balance, new balance after calculating the interest, and then a withdraw method. I'm stuck on printing the new balance to System.out since for some reason, I'm unable to get the new balance. 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.

    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.

Upvotes: 0

Views: 173

Answers (1)

vikarjramun
vikarjramun

Reputation: 1042

You would want to change your main method to the following:

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. Changing the balance of tda does not change the value of currentBalance. Thus, to update the value of currentBalance, you need to run currentBalance = tda.getcurrentBalance(); again.

Upvotes: 1

Related Questions