扫描程序 - java.util.NoSuchElementException [英] Scanner - java.util.NoSuchElementException

查看:118
本文介绍了扫描程序 - java.util.NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人看到这个有问题吗?第一个输入工作正常,但在第一个循环后,它不会要求再次输入值。我该如何解决这个问题?

Does anyone see a problem with this? First input works fine, but after the first loop, it doesn't ask to enter a value again. How do I fix this?

    int value;
    while(true)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a value");
        try 
        {
            value = scan.nextInt();
            System.out.println("value provided is: " + value);
            scan.nextLine(); // consumes "\n" character in buffer
        }
        catch(InputMismatchException e) // outputs error message if value provided is not an integer
        {
            System.out.println("Incorrect input type. Try again.");
            continue; // restarts while loop to allow for re-entering of a valid input
        }
        scan.close();
    }


推荐答案

移动 scan.close(); 之外,而循环。

还有你不必在每次迭代时构造 new Scanner 。也可以将声明移到循环外部。

Also you don't have to construct a new Scanner on each iteration. Move the declaration to outside the loop as well.

关闭 Scanner ,这将关闭 System.in 输入流。

When close the Scanner, this closes the System.in input stream.

所以现在当你尝试再次实例化时,它找不到任何打开的流,你就会得到那个例外。

So now when you try to instantiate it again, it doesn't find any opened stream and you'll get that exception.

这篇关于扫描程序 - java.util.NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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