Java scanner hasNext () not returning false
I am trying to continuously read input from the user until the custom types stop working. I test it by just typing "quit", but console.hasNext () doesn't seem to return false. Actually it seems that the program is blocked on line 7 (hasNext ()). Any ideas?
boolean bool = true;
while (bool) {
System.out.println("Type 'quit':");
Scanner console = new Scanner(System.in);
if (console.next().equals("quit")) {
System.out.println("You typed quit");
System.out.println("check: " + console.hasNext()); // This line doesnt print
bool = false;
}
}
source to share
If yours is Scanner
declared as System.in
, it will ask System.in
if the next value is received. The class in
will wait for the user to enter something and then return true.
Reserve hasNext()
for things like files where the input size is fixed. Thus, when a Scanner
file is requested, it has a specific hasNext()
.
Instead, I suggest grabbing the next value as a String and then checking if it is in integer format. If so then convert it, otherwise handle it however you want.
source to share