0

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.

Vikdor
  • 23,934
  • 10
  • 61
  • 84

3 Answers3

3

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

Community
  • 1
  • 1
Roger
  • 349
  • 3
  • 7
1

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.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
0

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

 tempData = in.nextDouble();
kosa
  • 65,990
  • 13
  • 130
  • 167