为什么 'For each' 不在 Java 中的未初始化数组上循环

Why doesn't 'For each' loop on a uninitialized array in Java

我在 Java 中有一个二进制搜索程序。 'for-each' 循环似乎在获取数组输入后不会增加计数器变量。但是,它确实适用于常规 'for' 循环。为什么 'for-each' 循环不能在这种情况下递增计数器?

import java.util.Scanner;

public class binarySearch {
    public static int rank(int key, int[] a) {
        int lo = 0;
        int hi = a.length - 1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (key > a[mid])
                lo = mid + 1;
            else if (key < a[mid])
                hi = mid - 1;
            else
                return mid;
        }
        return -1;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the key to be searched");
        int key = in.nextInt();
        System.out.println("\nEnter the number of elements in the array");
        int num = in.nextInt();
        int[] array = new int[num];

        for (int counter : array) {
            System.out.println("Enter the element of the array!");
            array[counter] = in.nextInt();
        }
        int result = rank(key, array);
        if (result == -1) {
            System.out.println("\n The given key is not found!\n");
        } else {
            System.out.println("\n The given key is found at position : " + (result + 1));
        }
    }
}

因为在

    for(int counter : array )
    {
        System.out.println("Enter the element of the array!");
        array[counter] = in.nextInt();
    }

counter 不是计数器。它是数组中的值。

您刚刚创建了数组而没有填充它,因此它将充满默认值。然后,您将遍历数组元素的 values,这意味着 counter 的值每次都将为 0。这个循环:

for(int counter : array )
{
    System.out.println("Enter the element of the array!");
    array[counter] = in.nextInt();
}

...大致等同于:

for (int i = 0; i < array.length; i++) {
    // Note: this will always be zero because the array elements are all zero to start with
    int counter = array[i]; 
    System.out.println("Enter the element of the array!");
    array[counter] = in.nextInt();
}

您实际上根本不想遍历数组中的原始值 - 您只想从 0 迭代到数组的长度(不包括),这很容易用 for循环:

for (int i = 0; i < array.length; i++) {
    System.out.println("Enter the element of the array!");
    array[i] = in.nextInt();
}

foreach 循环不是遍历数组索引而是遍历数组元素。