增强的for循环不适用于循环体内的Scanner [英] Enhanced for loop does not work with Scanner inside loop body

查看:150
本文介绍了增强的for循环不适用于循环体内的Scanner的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么认为不起作用?它只是打印零.但是,当我使用索引值为'i'的普通for循环并在循环体内使用'a [i]'时,此方法有效.

Why does think not work? It just prints zeros. However it works when I use a normal for loop with an index value 'i' and using 'a[i]' inside the body of the loop.

问题不在于打印循环,因为即使使用普通的for循环,它也不打印值.

The problem is not with the printing loop, as it does not print the values, even with a normal for loop.

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

推荐答案

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

When you access the element using enhanced for-loop: -

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

}

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

Here, int i is a copy of element in the array. When you modify it, the change will not get reflected in the array. That's why the array elements are 0.

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

So, you need to iterate using traditional for-loop and access the array elements on that index to assign values to it.

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

Even if your array was an array of some reference, it would still not work. That's because, the variable in a for-each is not a proxy for an array or Collection reference. For-each assigns each entry in the array to the variable in the loop.

因此,您的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.

So, the initialization of i in the loop, is not reflected in the array. And thus the array elements are null.

工作方式:-

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

  1. use traditional for loop: -

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

这篇关于增强的for循环不适用于循环体内的Scanner的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆