Search code examples
javaarraysfor-loopindexoutofboundsexceptionvariable-length

Error Using Length() Method in Array Within a For Loop


I created an array within a for loop to generate the cube of 1-9 in descending order. My code appears to work as I am able to run it without any syntax or runtime errors. However, whenever I try to use the length() method in my for loop, I get an "array out of bounds exception".

Here is my code without the length() method:

/**
 * This method prints out a cubes from one to nine in descending order
 */
public static void cubes()
{
    // create a fixed length array and hard code index number
    int[] values = new int[9];
    values[0] = 1;
    values[1] = 2;
    values[2] = 3;
    values[3] = 4;
    values[4] = 5;
    values[5] = 6;
    values[6] = 7;
    values[7] = 8;
    values[8] = 9;
    // Create variable to store cubed numbers
    double cubedNumber = 0;
    // Create for loop to run the array from 1-9 in descending order
    for (int counter = 8; counter > 0; counter--)
    {
        cubedNumber = Math.pow(values[counter], 3);
        System.out.println(values[counter] + " cubed is " + cubedNumber);
    }
}

This is my code using the length() method:

/**
 * This method prints out a cubes from one to nine in descending order
 */
public static void cubes()
{
    // create a fixed length array and hard code index number
    int[] values = new int[9];
    values[0] = 1;
    values[1] = 2;
    values[2] = 3;
    values[3] = 4;
    values[4] = 5;
    values[5] = 6;
    values[6] = 7;
    values[7] = 8;
    values[8] = 9;
    // Create variable to store cubed numbers
    double cubedNumber = 0;
    // Create for loop to run the array from 1-9 in descending order
    for (int counter = 8; counter <= values.length; counter--)
    {
        cubedNumber = Math.pow(values[counter], 3);
        System.out.println(values[counter] + " cubed is " + cubedNumber);
    }
}

Which gives me the following error: "java.lang.ArrayIndexOutOfBoundsException: -1 at arraysPractice.cubes(arraysPractice.java:31)" I'm required to use the length method in my for loop. Am I using the length() method incorrectly? In both instances, the program still generates the cubes per this output


Solution

  • The issue is here:

    for (int counter = 8; counter <= values.length; counter--)
    

    You're decrementing the counter; it only goes lower over time. It will always be <= values.length.

    Eventually it will reach -1, and produce an ArrayIndexOutOfBoundsException.

    Maybe you want...

    for (int counter = values.length - 1; counter >= 0; counter--)