请逐步解释此代码的输出:

public class My {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,1};
        for (int n : a) {
            a[n] = 0;
        }
        for (int n : a) {
            System.out.println(n);
        }
    }
}


我知道这是一个增强的循环。但不了解它如何与a[n]=0一起使用
为什么此代码输出00301?

最佳答案

您可以通过添加println语句来调试它:

    for (int n : a) {
        System.out.println("Changing element " + n + " of array from " + a[n] + " to 0");
        a[n] = 0;
    }


输出为:

Changing element 1 of array from 2 to 0
Changing element 0 of array from 1 to 0
Changing element 3 of array from 4 to 0
Changing element 0 of array from 0 to 0
Changing element 1 of array from 0 to 0

关于java - Java增强循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50115116/

10-12 20:58