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

时间:2012-11-06 13:43:19

标签: java loops for-loop

为什么认为不起作用?它只是打印零。但是,当我使用索引值为“i”的普通for循环并在循环体内使用“a [i]”时,它会起作用。

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

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);
    }
}
}

5 个答案:

答案 0 :(得分:6)

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

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

}

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

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

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

那么,你的enhanced for-loop: -

for (Integer i: arr) {
    i = new Integer();
}

转换为: -

for (int i = 0; i < arr.length; i++) {
    Integer i = arr[i];
    i = new Integer();
}

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

工作区: -

  1. 使用传统的for循环: -

    for (int i = 0; i < a.length; i++) {
        a[i] = sc.nextInt();
    }
    

答案 1 :(得分:2)

你的第一个for循环应该是循环的“经典”:

for (int i = 0; i < a.length; i++) {
    a[i] = s.nextInt();
}

答案 2 :(得分:2)

  

I = s.nextInt();

这是分配给局部变量i,而不是数组元素。基本上,

 for (int i : a) {
   //  body
 }

相同
for (int index = 0; index < a.length; index++) {
    int i = a[index];
    // body
}

因此,分配给i的任何内容都不会影响数组。

答案 3 :(得分:1)

声明

i=s.nextInt()

问问自己: - 你在这做什么?

您正在接受用户的输入。但是你在哪里存放它?我在里面?每次迭代都会被覆盖。 此外,i是本地范围的for循环。所以它不存在于包含循环之外。

因此,您将获得0... 0 ..0作为输出。

解决方案:

for (int i=0;i<a.length;i++) {
a[i] = s.nextInt();
}

将值用户输入存储在数组中。

答案 4 :(得分:-2)

您应该存储从s.nextInt();获得的值,这可以通过以下方式实现:

int j = 0;
for (int i : a){
      System.out.println("Enter number : ");
      a[j++]=s.nextInt();

}

这应该有用。