本文介绍了增强的“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循环给出了ArrayIndexOutOfBoundsException:

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

虽然这个 for 循环语句有效.为什么?代码有什么问题?

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:27