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();
}
At the end of the while loop you have written
scan.close()
. This will close the scanner preventing any further scans. Removing that statement would ensure your while loop keeps asking you for the number(will be an infinite loop in your case)Also,
scan.nextInt()
in effect ignores all new line and waits till you actually input a number and hit enter. So,scan.nextLine()
can be omitted. You need that only in case where you usescan.nextLine()
to fetch the value entered. In that case, the new line character is also read as an input, as a result of which you need an extra nextLine() call to consume it.Move
scan.close();
to outside thewhile
loop.Also you don't have to construct a new
Scanner
on each iteration. Move the declaration to outside the loop as well.When
close
the Scanner, this closes theSystem.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.
When you do
scan.close()
, it closes the underlyingSystem.in
stream. So in the next iteration it will not have anything to read.For example:
OUTPUT:
Check this question for more:
Is it safe not to close a Java Scanner, provided I close the underlying readable?