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

标签 java arrays for-loop indexoutofboundsexception variable-length

我在 for 循环中创建了一个数组,以按降序生成 1-9 的立方。我的代码似乎可以工作,因为我能够运行它而没有任何语法或运行时错误。但是,每当我尝试在 for 循环中使用 length() 方法时,都会收到“数组越界异常”。

这是我的代码,没有 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 at arraysPractice.cubes(arraysPractice.java:31)"我需要在 for 循环中使用 length 方法。我是否错误地使用了 length() 方法?在这两种情况下,程序仍然根据此 output < 生成立方体/p>

最佳答案

问题在这里:

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

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

最终它将达到-1,并产生 ArrayIndexOutOfBoundsException .

也许你想要...

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

关于java - 在 For 循环中的数组中使用 Length() 方法时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369513/

相关文章:

java - Java中的正则表达式非法字符

c - 数组类型和使用 malloc 分配的数组之间的区别

javascript - 基于外部逻辑的具有索引增量限制的可变数量的嵌套 While 循环

php - 在循环中插入 sql 查询是好事还是坏事?

c - 中断 for 循环内的 if 语句

java udp 服务器 100% cpu

java - hibernate : "Session is closed"虽然从未关闭(手动)

java - 如何使用 MongoDB 存储库在 Spring Boot 中通过 ID 以外的其他内容进行搜索

c - 从函数返回字符数组打印垃圾值但在函数中打印正常?

javascript - 如何更改 JSPsych 中刺激呈现的权重?