简体   繁体   中英

Repeating values

I have a project that has to ask the user for a credit balance and a rate, and then output how much you would have to pay for the next 12 months if you payed the mininum payment(calculated by: balance * 0.03, and if thats lower than 10 then the mininum payment is $10). I am cannot figure out why "balance * 0.03" will not increase in value of "minPay" as it loops.

import java.util.Scanner;
public class Project1Term2 
{
public static void main(String[] args) 
{
    Scanner in = new Scanner(System.in);

    System.out.println();
    System.out.print("Enter credit card balance: ");
    double balance = in.nextDouble();
    System.out.print("Enter interest rate: ");
    double interest = in.nextDouble();

    interest = interest / 100;

    for(int i = 0; i <= 12; i++)
    {
        Calculate out = new Calculate(balance, interest);
        System.out.println(out.getNewValue());
        balance = out.getNewValue();
    }   
}  
}

class Calculate
{
private final double rate;
private double balance;
private double minPay;
private double newBalance;

Calculate(double balance, double rate)
{
    this.balance = balance;
    this.rate = rate;
}

double getNewValue()
{
    if((balance * 0.03) < 10)
    {
        minPay = 10;
    }
    else
    {
        minPay = balance * 0.03;
    }
    newBalance = (balance - minPay) + (balance * rate);

    return newBalance;
}
}

You are creating a new instance of Calculate on every loop. That´s wrong on many ways. One consequence is that you´re never incrementing minPay , as each instance is used only once.

If you are simply looking for an answer as to why your balance wasn't decreasing, the answer is that your logic was incorrect.

newBalance = (balance - minPay) + (balance * rate);

Should be:

newBalance = balance + (balance * rate) - minPay ;

You want to add the interest to the current balance, and then subtract whatever the minimum payment is. Running your program with that logic gave me:

Enter credit card balance: 100
Enter interest rate: .1
90.1
80.1901
70.2702901
60.340560390099995
50.4009009504901
40.45130185144059
30.49175315329203
20.522244906445323
10.542767151351768
0.5533099185031194
-9.446136771578377
-19.455582908349953
-29.475038491258303

You could also work on some better coding practices. For example, you shouldn't instantiate a new instance of the class every loop. Instead, continue to use the same class instance. You should also check to see if the balance is 0, for example the output I got from running your program allowed me to pay into the negatives.

Hope this helps, feel free to ask questions if it doesn't make sense.

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