加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 增强的循环异常

发布时间:2020-12-14 16:35:14 所属栏目:Java 来源:网络整理
导读:参见英文答案 Enhanced ‘for’ loop causes an ArrayIndexOutOfBoundsException1个 在玩循环时创建以下代码.下面的代码将Fibonacci值存储到一个数组中,然后使用for循环打印它们. int [] numbers; numbers = new int[25]; numbers[0] = 1; numbers[1] = 1; S
参见英文答案 > Enhanced ‘for’ loop causes an ArrayIndexOutOfBoundsException1个
在玩循环时创建以下代码.下面的代码将Fibonacci值存储到一个数组中,然后使用for循环打印它们.
int [] numbers;
    numbers = new int[25];

    numbers[0] = 1;
    numbers[1] = 1;
    System.out.println("Initializing the array values");

    for(int i = 2; i < numbers.length; i++)
    {
        numbers[i] = numbers[i-1] + numbers[i-2];
    }

    System.out.println("Printing out Fibonacci values");

    for(int i = 0; i < numbers.length; i++)
    {
        System.out.print(numbers[i] + ",");
    }

上面的代码工作正常.我第一次把它扔在一起,我使用增强的for循环打印出值(代码中的第二个for循环).编译很好,但是当我运行它时,我得到以下内容;

Initializing the array values
Printing out Fibonacci values
1,1,2,3,8,34,377,17711,Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 34
at ArrayDemo.main(ArrayDemo.java:21)

我不知道出了什么问题.更改第二个循环不应更改值(您会注意到斐波纳契值是错误的(即缺少值)).而且我不明白为什么简单的增强型for循环会跳过索引.现在,这不是一个大问题,因为这不是一个项目或任何东西,它只是让我感到困惑,我无法弄清楚它为什么这样做.有线索吗?

增强的for循环就像这样;

for(int i : numbers)
    {
        System.out.print(numbers[i] + ",");
    }

解决方法

for(int i : numbers)
{
     System.out.print(numbers[i] + ",");
}

我在这里是数组中的元素,而不是索引.它可能比numbers.length更大.

例如,如果数字= {1,9},那么我将是1,9.但它的长度是4,所以当你循环其中的元素时,你正在尝试做数字[9]超过了它的大小.

你可能想要System.out.print(i“,”);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读