循环从扫描仪控制台读取 [英] reading from console with scanner in a loop for

查看:57
本文介绍了循环从扫描仪控制台读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法,这个想法是从控制台(键盘)上读取一连串的int数并将它们全部添加到ArrayList中的,我使用类Scanner读取了这些数,但是在for循环中不起作用,它会抛出 java.util.NoSuchElementException。

i have this method, and the idea is read from the console (keyboard) a sequence of int numbers and add all of them in an ArrayList, im using the class Scanner to read the numbers but in the for loop doesnt works, it throws "java.util.NoSuchElementException".

public static int mayorNumberSecuence(){
        System.out.println("Give me a size ");
        Scanner sn = new Scanner(System.in);
        int n = sn.nextInt();
        sn.close();
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<= n; ++i){
            System.out.println("Give me a number ");
            Scanner sn2 = new Scanner(System.in);
            int in = sn2.nextInt();
            list.add(in);
            sn2.close();
        }


推荐答案

首先,使用一台扫描仪代替而不是每次都重新创建扫描仪。另外,您的for循环还会多循环一次。

Firstly, use one scanner rather than recreating a scanner every time. Also, your for loop loops one extra time.

Scanner sn = new Scanner(System.in);
System.out.println("Give me a size ");
int n = sn.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < n; i++){
    System.out.println("Give me a number ");
    int in = sn.nextInt();
    list.add(in);
}
sn.close();

这对我来说很好,列表最后包含了我输入的所有数字。

This works fine for me, at the end the List contains all the numbers I entered.

您可以通过打印列表进行测试:

You can test it by printing the list:

System.out.println(list);

旧代码的问题是使用 .close() 在扫描仪上,它将关闭基础 InputStream ,即 System.in 。如果关闭 System.in ,则无法在下一个扫描仪中再次使用它。这就是为什么使用一个扫描仪可以解决该问题的原因。

The problem with your old code is that when you use .close() on the Scanner, it closes the underlying InputStream, which is System.in. If you close System.in, you cannot use it again in the next Scanner. This is why using one Scanner fixes the issue.

这篇关于循环从扫描仪控制台读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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