jakivey32 - 1 year ago 67

Java Question

I have a loop in Java that is meant to calculate values for an array and put them in each index.

Here is what I have:

`for(int i = 15; i <= 30; i += 5){`

double rate = 0.03;

int index = 0;

payments[index] = LoanCalculator(initLoan, rate, i*12);

index++;

}

System.out.println();

System.out.printf("%-2.1f%c", 3.0, percent);

System.out.printf("%13.2f %9.2f %9.2f %9.2f", payments[0], payments[1], payments[2], payments[3]);

}

Here is what it outputs (note: there is other code that prints out the top portion of the output) :

`Years: 15 20 25 30`

__________________________________________________

3.0% 421.60 0.00 0.00 0.00

There is obviously a math error in here somewhere which is really bugging me because I passed the exact same parameters earlier and it was returning correct values.

What I am concerned with is that there are no values being placed in the last three indices. Can anyone explain to me what I have done wrong here?

P.S. Here is the LoanCalculator method I am using:

`public static double LoanCalculator(double loan, double rate, int payments)`

{

double r = rate/12;

double monPay = (loan * r * Math.pow(1+r, payments))/((Math.pow(1+r, payments))-1);

return monPay;

}

Any help is appreciated.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Consider this code

```
for(int i = 15; i <= 30; i += 5){
double rate = 0.03;
int index = 0;
```

within your `for`

loop your are re-setting `index`

to zero each time

so the effect of

```
index++;
```

is nullified

Move the declaration of index to before your `for`

loop

```
double rate = 0.03;
int index = 0;
for(int i = 15; i <= 30; i += 5){
payments[index++] = LoanCalculator(initLoan, rate, i*12);
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**