增强的'for'循环导致ArrayIndexOutOfBoundsException [英] Enhanced 'for' loop causes an ArrayIndexOutOfBoundsException

查看:134
本文介绍了增强的'for'循环导致ArrayIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

import java.util.Scanner;

public class Arrays {
    public static void main(String[] args) {
        Arrays psvm = new Arrays();
        psvm.start();
    }

    public void start() {
        Scanner ben = new Scanner(System.in);
        int[] arr = new int[4];
        int[] arrs = new int[4];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = ben.nextInt();
        }
        check(arr, arrs);
    }

    public void check(int arr[], int arrs[]) {
        for (int i = 0; i < arr.length; i++) {
            arrs[i] = arr[i];
        }
        for (int i : arrs) {
            System.out.println(arrs[i]);
        }
    }
}

增强 for loop给出 ArrayIndexOutOfBoundsException

for (int i : arrs) {
    System.out.println(arrs[i]);
}

循环语句有效。为什么?代码出了什么问题?

While this for loop statement works. Why? What's wrong with the code?

for (int i = 0; i < arrs.length; i++) {
    System.out.println(arrs[i]);
}


推荐答案

在这种情况下, i 将被分配给数组中的每个元素 - 它是不是数组的索引。

In this case, i will be assigned to each element in the array - it is not an index into the array.

你想要做的是:

for(int i : arrs)
{
    System.out.println(i);
}

在你的代码中,你试图在数组索引处选择整数由迭代对象引用。换句话说,您的代码相当于:

In your code, you're trying to select the integer at the array index referenced by the iteration object. In other words, your code is equivalent to:

for(int idx = 0; idx < arrs.length; idx++)
{
    int i = arrs[idx];
    System.out.println(arrs[i]);
}

这篇关于增强的'for'循环导致ArrayIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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