简体   繁体   中英

For Loop in Array (Java) Index Out of Bounds

I'm having a hard time using an array in a for loop that is supposed to cube numbers 1-9 in descending order. I keep getting an out of bounds error and the cubed values are completely off. I would greatly appreciate an explanation as to where I am going wrong with thinking about arrays. I believe the issue is with my index, but I'm struggling to explain why.

System.out.println("***** Step 1: Using a for loop, an array, and the Math Class to get the cubes from 9-1 *****");
    System.out.println();
    // Create array
    int[] values = new int[11];
    int[] moreValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    // Create variable to store cubed numbers
    double cubedNumber = 0;
    // Create for loop to count in descending order
    for (int counter = 9; counter < moreValues.length; counter--)
    {
        cubedNumber = Math.pow(counter,3);
        System.out.println(moreValues[counter] + " cubed is " + cubedNumber);
    }

Output

Your main bug is the loop termination condition counter < moreValues.length , which if you're counting down will always be true .

Instead, check for the index being at or above zero:

for (int counter = 9; counter >= 0; counter--)

Your other bug is you're cubing the index , not the number pointed to by the index, so code this instead;

cubedNumber = Math.pow(moreValues[counter], 3);

To reduce confusion, you're better using an industry standard name for the loop variable, like i or where the loop variable is being used as an index to an array, index is often used and can improve code clarity.

Try:

for (int counter = moreValues.length; counter >= 1; counter--)
{
    cubedNumber = Math.pow(counter,3);
    System.out.println(moreValues[counter-1] + " cubed is " + cubedNumber);
}

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