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();
}
Move scan.close();
to outside the while
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 the System.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With