ava错误ArrayIndexOutOfBoundsExcept

ava错误ArrayIndexOutOfBoundsExcept

本文介绍了每次循环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

推荐答案

对于您情况下的每个循环,将解释为:

For each loop in your case will be explained like:

for (int i : numbers) {

数组编号中的每个整数都将被逐一放置在i

every integer in array numbers will be placed in i one by one

所以,您做错了什么:

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

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

i不会像传统的for循环那样增加evrytime循环,此处i携带实际值

i will not be increasing evrytime loop proceed like in the traditional for loop, here i carry the actual value

所以您应该从numbers[i]%2==0更改为i%2==0

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

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

08-14 06:27