Java while 循环中的扫描器输入验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19950713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scanner input validation in while loop
提问by Kurt Bourbaki
I've got to show Scanner inputs in a whileloop: 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 输入:用户必须插入输入,直到他写下“退出”。所以,我必须验证每个输入以检查他是否写了“退出”。我怎样才能做到这一点?
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?
这不起作用。如何验证每个用户输入?
采纳答案by Ruchira Gayan Ranaweera
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.
问题是nextLine()“将这个扫描器推进到当前行之后”。所以,当你打电话nextLine()
的while
状态,不保存返回值,你已经失去了行了用户的输入。nextLine()
对第 3 行的调用返回不同的行。
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);
}
回答by mosaad
always check if scanner.nextLine is not "quit"
始终检查scanner.nextLine 是否不是“退出”
while (!scanner.nextLine().equals("quit")) {
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); // This stores given inputs on db
}
}
回答by user2986555
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
}