在 For 循环中的数组中使用 Length() 方法时出错

Error Using Length() Method in Array Within a For Loop

我在 for 循环中创建了一个数组,以降序生成 1-9 的立方体。我的代码似乎可以正常工作,因为我能够 运行 它而没有任何语法或 运行 时间错误。但是,每当我尝试在我的 for 循环中使用 length() 方法时,我都会得到一个 "array out of bounds exception".

这是我的没有 length() 方法的代码:

/**
 * This method prints out a cubes from one to nine in descending order
 */
public static void cubes()
{
    // create a fixed length array and hard code index number
    int[] values = new int[9];
    values[0] = 1;
    values[1] = 2;
    values[2] = 3;
    values[3] = 4;
    values[4] = 5;
    values[5] = 6;
    values[6] = 7;
    values[7] = 8;
    values[8] = 9;
    // Create variable to store cubed numbers
    double cubedNumber = 0;
    // Create for loop to run the array from 1-9 in descending order
    for (int counter = 8; counter > 0; counter--)
    {
        cubedNumber = Math.pow(values[counter], 3);
        System.out.println(values[counter] + " cubed is " + cubedNumber);
    }
}

这是我使用 length() 方法的代码:

/**
 * This method prints out a cubes from one to nine in descending order
 */
public static void cubes()
{
    // create a fixed length array and hard code index number
    int[] values = new int[9];
    values[0] = 1;
    values[1] = 2;
    values[2] = 3;
    values[3] = 4;
    values[4] = 5;
    values[5] = 6;
    values[6] = 7;
    values[7] = 8;
    values[8] = 9;
    // Create variable to store cubed numbers
    double cubedNumber = 0;
    // Create for loop to run the array from 1-9 in descending order
    for (int counter = 8; counter <= values.length; counter--)
    {
        cubedNumber = Math.pow(values[counter], 3);
        System.out.println(values[counter] + " cubed is " + cubedNumber);
    }
}

这给了我以下错误:“java.lang.ArrayIndexOutOfBoundsException: -1 在 arraysPractice.cubes(arraysPractice.java:31)" 我需要在我的 for 循环中使用 length 方法。我是否错误地使用了 length() 方法?在这两种情况下,程序仍然会生成立方体根据这个 output

问题在这里:

for (int counter = 8; counter <= values.length; counter--)

您正在递减计数器;它只会随着时间的推移而降低。它将永远是 <= values.length.

最终它会达到-1,并产生一个ArrayIndexOutOfBoundsException

也许你想要...

for (int counter = values.length - 1; counter >= 0; counter--)

你的条件是counter <= values.length

values.length 的值是 9,计数器的值从 8 开始递减到 7,6,5,4,3,2,1,0,当它的值达到 -1 时,仍然是 counter < = values.length 对于 -1 是正确的。在这段代码中

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

当您将 -1 作为值数组中的索引传递时,它会给您 java.lang.ArrayIndexOutOfBoundsException 异常。

你以这种方式循环使它运行很好。

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