Trying to write a method that checks user input in JAVA, getting NoSuchElementException [duplicate]

本小妞迷上赌 提交于 2019-12-12 03:37:58

问题


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) the number must be positive and real-valued (double)

the next 4 times the condition is

b) the number must be greater than 1

This is my method:

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

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.


回答1:


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

See: Using Scanner.next() to get text input




回答2:


If you call in.close() in the method, you need some way of determining if it is the last input or not.

I would recommend putting the scanner in your main method, passing the scanner in to the method, and then closing it when you're done with all your input.

What I suspect is happening is you're sending the input piped as if from a file. The first scanner buffers all the input, and when you close and re-open it, you end up losing the data that was buffered to the first scanner. I can't guarantee that, but that's what it looks like.




回答3:


After while loop it tries to call, by this line there may not be any inputs.

 tempData = in.nextDouble();


来源:https://stackoverflow.com/questions/12410173/trying-to-write-a-method-that-checks-user-input-in-java-getting-nosuchelementex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!