java - 数组中的 For 循环 (Java) 索引越界

标签 java arrays indexoutofboundsexception

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

Output

最佳答案

你的主要错误是循环终止条件 counter < moreValues.length ,如果您倒数,则该结果永远为真

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

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

您的另一个错误是您正在计算索引的立方,而不是索引指向的数字,因此请改为编码;

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

为了减少困惑,您最好为循环变量使用行业标准名称,例如 i或者当循环变量被用作数组的索引时,index经常使用,可以提高代码清晰度。

关于java - 数组中的 For 循环 (Java) 索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47358711/

相关文章:

java - j2ee Web 应用程序的标准项目/包结构

java - 将两个 DAO 中的数据合并到一个 TO 中

c++ - 排序二维动态数组 C++

Java - IndexOutOfBoundsException

c#删除元素后的Parallel For Loop索引异常

java - 比较java中的两个字符串集并输出二进制(匹配/不)数组

Java + Google map API + GWT + 地理编码尝试 : Getting this exception at run time- compiling fine

java - ArrayList 上的 Junit 测试

php - 是否可以将数组转储到 mysql 文本字段中并将其作为数组读回?

java.lang.StringIndexOutOfBoundsException : Exception 异常