For-Each 循环 Java 错误 ArrayIndexOutOfBoundsException [英] For-Each Loop Java Error ArrayIndexOutOfBoundsException

查看:46
本文介绍了For-Each 循环 Java 错误 ArrayIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我需要一个 for-each 循环,它计算给定数组中偶数的数量,并为每个偶数增加变量 even.当我使用标准的 for 循环,即 (i = 0; i < numbers.length; i++;) 时,代码工作正常.但是,我的作业要求我针对这个特定问题使用 for-each 循环.我做错了什么吗?

In my program I need a for-each loop which counts the number of evens in the given array and increments the variable even for each one. When I use a standard for loop, i.e. (i = 0; i < numbers.length; i++;), then the code works fine. However, my assignments requires me to use a for-each loop for this particular problem. Am I doing something wrong?

int [] numbers = new int[8];
int even = 0;
int odd = 0;

for (int i = 0; i < numbers.length; i++) { 
    numbers[i] = (int)(Math.random() * 51 + 50);
}

for (int i : numbers) {
    if (numbers[i] % 2 == 0) {
        even++;
    }
    else
        odd++;

这会引发错误:

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

推荐答案

if (numbers[i] % 2 == 0) {

在您的 foreach 循环中,您不需要使用索引访问它.只需 i 就足够了,因为 foreach 继续为您提供您正在使用的数组/集合中的 element 直接(不是索引).

Inside your foreach loop, you need not to access it with index. Just i is enough as foreach keep on gives you the element directly (not the index) inside the array/collection you are using.

if (i % 2 == 0) {

<小时>

for (int i : numbers) {
        if (i % 2 == 0) {
            even++;
        }
        else{
            odd++;
        }
  }

<小时>

通过检查第一个循环本身的偶数或奇数,您实际上可以通过完全消除第二个循环来缩短代码.


You can actually shorten your codes by eliminating the second loop completely by checking the even or odd in first loop itself.

这篇关于For-Each 循环 Java 错误 ArrayIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆