for 循环在数组 (java) 索引越界



我很难在 for 循环中使用应该按降序立方数字 1-9 的数组。我不断收到越界错误,立方体值完全关闭。我将非常感谢解释我在考虑数组时出错的地方。我相信问题出在我的索引上,但我正在努力解释原因。

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);
    }

输出

你的主要错误是循环终止条件counter < moreValues.length,如果你倒计时,这将永远是真的

相反,请检查索引是否等于或大于零:

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

您的另一个错误是您正在对索引进行立方体,而不是索引指向的数字,因此请改为编写代码;

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

为了减少混淆,最好为循环变量使用行业标准名称,例如i或循环变量用作数组的索引,index经常使用并且可以提高代码清晰度。

尝试:

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

最新更新