尝试编写一种方法来检查JAVA中的用户输入,并获得NoSuchElementException [英] Trying to write a method that checks user input in JAVA, getting NoSuchElementException

查看:42
本文介绍了尝试编写一种方法来检查JAVA中的用户输入,并获得NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一种方法来处理来自控制台应用程序中用户的所有输入.我称此方法共5次.第一次,条件是

I am trying to write a method to handle all my input from the user in a console application. I call this method a total of 5 times. The first time, the condition is

a)该数字必须为正且实数值(双精度)

a) the number must be positive and real-valued (double)

接下来的4倍的情况是

b)该数字必须大于1

b) the number must be greater than 1

这是我的方法:

private static double numChk(int errNum) {

    final String[] ERROR_MESSAGE = {
            "\nPlease enter only positive, real-valued numbers",
            "\nPlease enter only positive numbers greater than 1" };
    Scanner in = new Scanner(System.in);
    double tempData;

    while (!in.hasNextDouble()) {
        System.out.println(ERROR_MESSAGE[errNum]);
        System.out.print("  Please try again: ");
        in.next();
    }
    tempData = in.nextDouble();

    // in.close();
    return tempData;
}

这是对此方法的示例调用:

this is an example call to this method:

 do {
        System.out
                .println("Please enter only positive, real-valued numbers");
        System.out.print("  Enter a constant: ");
        mu = numChk(0);
    } while (mu <= 0);

注意"//in.close();"用我写的方法如果不关闭扫描仪,则此方法可以正常工作.但是,我的作业要求我确保关闭所有打开的输入流.如果我关闭方法中的输入流并重新打开它,则会收到NoSuchElementException.我知道我可以将所有这些放入我的main方法中并在其末尾关闭输入,但是,我想知道是否有一种方法可以做到这一点(输入验证,多次)并能够关闭输入流.

note the "// in.close();" in the method I wrote. Without closing the Scanner in, this method works fine. However, my assignment requires me to make sure I close all open input streams. if I close the input stream in the method and re-open it, I get a NoSuchElementException. I know I could just put all of this into my main method and close the input at the end of it however, I would like to know if there is a way to do this (input validation, multiple times) and be able to close the input stream.

推荐答案

当您调用in.close()时,您还将关闭System.in.下次尝试使用新的扫描仪时,它将尝试使用封闭的System.in,这就是为什么当您尝试从中读取时会出现异常的原因

When you call in.close() you are also closing the System.in. The next time you try to use a new Scanner, it will try to use a closed System.in, and that is why you get an exception when you try to read from it

请参阅:使用Scanner.next()获取文本输入

这篇关于尝试编写一种方法来检查JAVA中的用户输入,并获得NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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