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.