View Full Version : New to CF and new to Java! Please help!

02-06-2012, 07:27 PM
Hi all,

I'm enrolled in a Java class and I'm having trouble with an array in a for loop.

Here's the entire code:

import java.text.DecimalFormat;

* @author KenanCross
public class MortgageCalcArray {
int i; // counter
int termLimit;
int payments;
double balPdCalc; //Calculated result of balPd and balPd2
double loanCalc; //Power of Calculation for compound interest
double[] rates = {0.0525,0.055,0.0575}; //Array containing interest rates
double[] results = new double[3]; //Array containing computed results
int[] lengths = {7,15,30}; //Array containing values of corresponding years.
double annualRate; //Computed Annual Rate
double interestPlus; // rate + 1
double interestAdj;
double interestExp;
double principle; /* Principle loan amount */
double monthlyPayment; /* Calculated Monthly Payment */
DecimalFormat dec;
DecimalFormat percentage;

public static void main (String args[]){
MortgageCalcArray calc = new MortgageCalcArray();

public MortgageCalcArray(){
principle = 200000;
dec = new DecimalFormat ("$0.00");
percentage = new DecimalFormat("0.00%");

public void calculatePaymentAmount(){
for (i=0; i <= lengths.length; i++)
annualRate = (rates[i]/(12));
payments = (12) * (lengths[i]);
interestAdj = (annualRate)+(1);
interestExp = Math.pow(interestAdj, payments);
results[i] = principle * (annualRate * interestExp)/(interestExp - 1);

public void printPaymentAmount (){
System.out.println("Your Loan Amount is "+ dec.format(principle));
System.out.println("\t Your monthly payment at " + (lengths[0]) + " years, with a " + percentage.format (rates[0]) + " rate, is " + dec.format (results[0]));

I'm trying to get the for loop to call the different values in the array in conjunction with each loop iteration from variable i, then store the results in the results array at the bottom.

I keep getting a java.lang.ArrayIndexOutOfBoundsException: 3 throw error, yet I can't figure out where I went wrong.

Any help you can give would be greatly appreciated!

02-07-2012, 03:15 AM
Java is 0 based. When you iterate up to a size using array.length, that would say you have 3 items within your array. These items are located at 0, 1, and 2. When you use <= it is moving from 0 through 3 inclusive, so its attempting to access a 4th element and tosses that error.

02-12-2012, 10:31 PM
Thanks for your response! I was able to figure it out.