增强的for循环不适用于循环体内的Scanner

Vik*_*ram 2 java loops for-loop

为什么认为不起作用?它只是打印零.然而,当我使用索引值为"i"的普通for循环并在循环体内使用"a [i]"时,它可以工作.

问题不在于打印循环,因为它不会打印值,即使是正常的for循环也是如此.

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    int[] a = new int[5];
    for (int i : a)
    {
        System.out.println("Enter number : ");
        i=s.nextInt();

    }
    System.out.println("\nThe numbers you entered are : \n");
    for (int i : a)
    {
        System.out.println(i);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 6

使用增强的for循环访问元素时: -

for (int i : a)
{
    System.out.println("Enter number : ");
    i=s.nextInt();

}
Run Code Online (Sandbox Code Playgroud)

这里int i是数组中元素的副本.修改它时,更改不会反映在数组中.这就是数组元素为0的原因.

因此,您需要使用传统的for循环进行迭代并访问其上的数组元素以为index其赋值.

即使你的数组​​是一些引用的数组,它仍然无法工作.这是因为,for-each中的变量不是数组或Collection引用的代理.For-each将数组中的每个条目分配给循环中的变量.

那么,你的enhanced for-loop: -

for (Integer i: arr) {
    i = new Integer();
}
Run Code Online (Sandbox Code Playgroud)

转换为: -

for (int i = 0; i < arr.length; i++) {
    Integer i = arr[i];
    i = new Integer();
}
Run Code Online (Sandbox Code Playgroud)

因此,i循环中的初始化不会反映在数组中.因此数组元素是null.

工作方式: -

  1. 使用传统的循环: -

    for (int i = 0; i < a.length; i++) {
        a[i] = sc.nextInt();
    }
    
    Run Code Online (Sandbox Code Playgroud)