0

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

iMagicMango
  • 73
  • 1
  • 10
  • 3
    As soon as `counter` reaches -1, it will try and read a value of the array at an index that doesn't exist, thus, Out Of Bounds. Might be better served with `for (int counter = (moreValues.length)-1; counter >= 0; counter--)` (although why you would want to count down instead of up in your case is beyond me). – AntonH Nov 17 '17 at 20:24
  • 2
    You do realize that in your `Math` line you're cubing the counter, not `moreValues[counter]` ? – Davy M Nov 17 '17 at 20:25
  • Also worth checking out, although not quite a duplicate: https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – AntonH Nov 17 '17 at 20:29

2 Answers2

1

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Thank you for this explanation! Would you be able to also explain why my index is 11, but when I declare the values in moreValues, I only have 10 digits? My textbook hasn't really done a good job of explaining this and I'm working primarily from there. – iMagicMango Nov 17 '17 at 20:50
0

Try:

for (int counter = moreValues.length; counter >= 1; counter--)
{
    cubedNumber = Math.pow(counter,3);
    System.out.println(moreValues[counter-1] + " cubed is " + cubedNumber);
}
Vijaya Pandey
  • 4,252
  • 5
  • 32
  • 57