简体   繁体   中英

Account Class Java OOP

I have created an account class but the after the first calculation the it continues and doubles the second line. Have I missed anything in the code.

public class Account
{
    private double balance; //STATE
    private double interestRate; //STATE
    private double rate;//STATE

    public Account()
    {
        balance = 0; 
        interestRate = 0;
    }

    public Account(double amount, double interestRate)
    {
        balance = amount;   
        rate = interestRate;

    } 

    public void deposit(double amount)
    {
        balance=balance+amount;
    }

    public void withdraw(double amount)
    {
        balance = balance - amount;
    }

    public void setInterest(double rate)
    {
        balance = balance + balance * rate;
        //this.setInterst = setInterest;  
        //setInterest = InterestRate / 12;
    }

    public double computeInterest(int n)
    {
        balance=Math.pow(balance*(1+rate),n/12); 
        return balance;
    }

    public double getsetInterest()
    {
        return rate;
    }

    public double getBalance()
    {
        return balance;
    }

    public void close()
    {
        balance =0;
    }

}

public class TestAccountInterest
{
    public static void main (String[] args)
    {
        Account acc1 = new Account(500, 0.1);//0.10);
        Account acc2 = new Account(400, 0.2); //0.20);

      /*************************************
       ACC1 ACCOUNT BELOW
       *************************************/
        acc1.deposit(500);
        acc1.withdraw(300);
        acc1.computeInterest(12);
        acc1.computeInterest(24);
        System.out.println(acc1.computeInterest(12));

        /**************************************
        ACC2 ACCOUNT BELOW
         **************************************/
        acc2.withdraw(200);
        acc2.deposit(800);
        acc2.computeInterest(24);
        System.out.println(acc2.computeInterest(24));

    }

}

I don't know whether I have missed out something or that I have wrote the code wrong.

    acc1.computeInterest(12);
    acc1.computeInterest(24);

It looks to me that what you want is that calling these functions only return the computed interest but it shouldn't change your balance variable.

Just return the computed value without saving it in @balance variable.

This is my interpretation of your question, you were a little bit vague.

You have used the method computeinterest(int n) twice for the object acc1. the first time when you have used acc1.computeInterest(12) you get a value for it, but as you have used acc1.computeInterest(24) after that you are getting the answer incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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