Havanna Ransom
Havanna Ransom

Reputation: 77

Java for loop passing variable

I have the following code :

double getTotalPayments(){
    for (int i = 0 ; i == periodsPerYear * years ; i++){
      double balance =+ Math.round(initialBalance - (monthlyPayment-((interestRate/periodsPerYear) *initialBalance))*100.00)/100.00;
      initialBalance =- balance;
      if(i == periodsPerYear*years){
        return balance;
        break;
      }
    }
    return balance;
  }

I'm trying to pass the double variable 'balance' for the method to return. I have to use the for loop to calculate the total amount of payments. Any suggestions on how to fix it? I've tired everything I can think of.

Upvotes: 0

Views: 130

Answers (3)

How can you return balance when "balance" is only a local variable in for loop? And another like @NomadMaker said that the condition for the for loop should be "i < periodPerYear * years".

Upvotes: 0

Karan Malhotra
Karan Malhotra

Reputation: 145

It should be

double balance += Math.round(initialBalance - 
(monthlyPayment-((interestRate/periodsPerYear) 
 *initialBalance))*100.00)/100.00;

initialBalance -= balance;

Upvotes: 0

Andy Xia
Andy Xia

Reputation: 41

I think you're just missing a few things within the code. It would probably go something like this. You were just missing the bits within the method declaring that it's either a public or private method, and that you weren't calling in the Int Variable balance.

public double getTotalPayments(int balance){
for (int i = 0 ; i == periodsPerYear * years ; i++){
  double balance =+ Math.round(initialBalance - (monthlyPayment-((interestRate/periodsPerYear) *initialBalance))*100.00)/100.00;
  initialBalance =- balance;
  if(i == periodsPerYear*years){
    return balance;
    break;
  }
}
return balance;

Please let me know if that works!

Upvotes: 1

Related Questions