I have a problem with Scanner in a while loop.
Whenever I have a while (true) loop reading from scanner, as soon as I close scanner object, the while loop starts to iterate eternally thinking I closed stream. But I open and close stream in a separate method, that as I imagine should be opening and closing it each time the method is called, but it doesn’t. What currently helps is creating Scanner object outside the loop and sending it as a parameter to the method, plus adding scannerObject.next() method.
I don’t want to change loop conditions. Are there normal ways to avoid this error?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//testing how to have a while loop that only stops if q is entered
Scanner userInput = new Scanner(System.in);
while(true) {
int number = input(userInput);
switch(number) {
case 0: // returns 0 for Invalid input
System.out.println("Invalid input. Enter an integer or q to Quit");
break;
case -1: // returns 1 to quit the program
//
System.out.println("You chose to quit. Good-bye");
System.exit(0);
break;
default: // default is done when the input returns an integer, so valid input
System.out.println("You entered " + number);
break;
}
//System.out.println("I am now after the while loop");
}// end of while(true) loop for userinput
}
private static int input(Scanner userInput) {
System.out.println("Enter an integer or q to Quit the program: ");
int result = 0;
if(userInput.hasNextInt()) {
result = userInput.nextInt();
}
else {
if(userInput.hasNext("q")) {
result = -1;
}
else {
userInput.next();
// result = 0;
}
}
return result;
}
}