while 循环中的扫描器输入验证 [英] Scanner input validation in while loop
问题描述
我必须在 while 循环中显示扫描仪输入:用户必须插入输入,直到他写下退出".所以,我必须验证每个输入以检查他是否写了退出".我该怎么做?
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?
推荐答案
问题在于 nextLine() "将这个扫描器推进到当前行之后".因此,当您在 while
条件中调用 nextLine()
并且不保存返回值时,您已经丢失了用户输入的那一行.第 3 行对 nextLine()
的调用返回了另一行.
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.
你可以试试这样的
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);
}
这篇关于while 循环中的扫描器输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!