gpt4 book ai didi

java - 对于每个循环异常

转载 作者:行者123 更新时间:2023-11-29 09:56:30 24 4
gpt4 key购买 nike

我在第二行打印中遇到异常。

int num[] = {50,20,45,82,25,63};
System.out.print("Given number : ");
for(int d:num){
System.out.print(" " + num[d]);
}

控制台输出为

Given number : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50

为什么 d 不取所有数组元素而只取 50 个?

最佳答案

for(int d:num) 循环中,每个项目都由 d 表示,而不是 num[d]

所以,这是应该如何完成的。

for(int d:num){
System.out.print(" " + d);
}

一个简单的试运行将告诉您哪里出了问题。

For the first loop your statement will come down to num[50] which is not available anywhere, so you get the exception.


但是,如果您尝试使用索引,那么下面的一个简单技巧就可以解决问题

int index = 0;
for(int d:num){
System.out.print(" " + num[index++]);
}

但老实说,我认为这不是解决问题的正确方法。

关于java - 对于每个循环异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9975247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com