如何在java中对数组使用for-each循环打印奇偶数的代码



我写了一段代码,应该在Java中使用for-each循环从数组中打印奇数和偶数,但不幸的是它显示

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 22"

即使一些答案被打印在编译器中,它也不像它应该的那样。输出如下所示:

Even numbers in the Array are:
10
6
4
2
.
.

但是它是这样显示的:

Even numbers in the Array are:
10
14
4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 22

有人能帮忙吗?

这是我的代码供你参考。

public class Main {
public static void main(String[] args) {
int[] num = {1,3,9,10,6,5,4,2,22,14,15,7,8};
System.out.println("Even numbers in the Array are:");
for (int i : num) {
if (num[i] % 2 == 0) {
System.out.println(num[i]);
}
}
System.out.println("The Odd numbers in the Array are:");
for (int i : num) {
if (num[i] % 2 != 0) {
System.out.println(num[i]);
}
}
}
}

我写了一个应该打印奇数和偶数的代码在Java中使用for-each循环从数组中取出但不幸的是它显示了

线程"main"异常java.lang.ArrayIndexOutOfBoundsException:22"。

这是因为您正在使用数组的元素作为数组本身的索引。它在22处失败,因为它是数组中第一个大于数组大小的值。

你有索引基循环

for(int i=0; i<num.length; i++){
if( num[i]%2 ==0) {
System.out.println(num[i]);
}
}

和(除其他外)增强的for循环允许您直接遍历(例如)数组的内容,而无需显式指定索引。

for-each Loop Sytnax

Java for-each循环的语法是:
for(dataType item : array) {
...
}

,

array—数组或集合
item—数组/集合的每一项都被赋值给这个变量dataType
数组/集合的数据类型

这使得代码更简洁,也更不容易出错:

for(int n : num) {
if(n%2 == 0) {
System.out.println(n);
}
}

这个循环非常有用,因为很多时候,除了访问数组中的元素外,我们希望遍历数组中的所有元素,而不需要真正关心索引。

for(int i : num) 

这里"我不是数组的索引,这就是元素,因此,您不需要以这种方式获取值

num[i]

仅仅以这种方式指代就足够了

i

所以最好不要使用变量名"i"在这种情况下,但

for (number: numbers) 

例如而不是

最新更新