繁体   English   中英

For循环数组(Java)索引超出范围

[英]For Loop in Array (Java) Index Out of Bounds

我很难在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 ,如果您递减计数它将始终为true

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

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

您的另一个错误是您要查询索引 ,而不是索引所指向的数字,因此请编写此代码;

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

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

尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM