Scanner input validation in while loop
Solution 1
The problem is that nextLine() "Advances this scanner past the current line". So when you call nextLine()
in the while
condition, and don't save the return value, you've lost that line of the user's input. The call to nextLine()
on line 3 returns a different line.
You can try something like this
Scanner scanner=new Scanner(System.in);
while (true) {
System.out.println("Insert question code:");
String question = scanner.nextLine();
if(question.equals("quit")){
break;
}
System.out.println("Insert answer code:");
String answer = scanner.nextLine();
if(answer.equals("quit")){
break;
}
service.storeResults(question, answer);
}
Solution 2
Try:
while (scanner.hasNextLine()) {
System.out.println("Insert question code:");
String question = scanner.nextLine();
if(question.equals("quit")){
break;
}
System.out.println("Insert answer code:");
String answer = scanner.nextLine();
service.storeResults(question, answer); // This stores given inputs on db
}
Kurt Bourbaki
- Keenformatics This is where I write guides about the mistakes I daily do and the problems I (more or less) daily solve. Python. Ruby on Rails. Experiences with JEE, Struts, Spring and Tiles.
Updated on July 09, 2022Comments
-
Kurt Bourbaki almost 2 years
I've got to show Scanner inputs in a while loop: the user has to insert inputs until he writes "quit". So, I've got to validate each input to check if he writes "quit". How can I do that?
while (!scanner.nextLine().equals("quit")) { System.out.println("Insert question code:"); String question = scanner.nextLine(); System.out.println("Insert answer code:"); String answer = scanner.nextLine(); service.storeResults(question, answer); // This stores given inputs on db }
This doesn't work. How can I validate each user input?
-
Kurt Bourbaki over 10 yearsWhat's the difference between
while (scanner.hasNextLine())
andwhile (true)
(like in Ruchira's answer) in this case? -
user2986555 over 10 yearswhile(true) will terminate only in break and while(scanner.hasNextLine()) terminate at EOF.
-
Kurt Bourbaki over 10 yearsBut how can it reach the end of file if there will always be a
scanner.nextLine()
(even if empty)? -
drewteriyaki over 6 yearsWhy is it that the
Scanner scanner = new Scanner(System.in)
is outside the while loop? -
LarsH almost 6 years@drewteriyaki: You don't want a new
Scanner
created for every user input. A single Scanner on the single system input stream keeps a consistent state on that stream.