Java while循环中的扫描仪输入验证
我必须在while循环中显示扫描仪输入:用户必须插入输入,直到写入“退出”。所以,我必须验证每个输入,以检查他是否写“退出”。我该怎么做Java while循环中的扫描仪输入验证,java,loops,while-loop,java.util.scanner,Java,Loops,While Loop,Java.util.scanner,我必须在while循环中显示扫描仪输入:用户必须插入输入,直到写入“退出”。所以,我必须验证每个输入,以检查他是否写“退出”。我该怎么做 while (!scanner.nextLine().equals("quit")) { System.out.println("Insert question code:"); String question = scanner.nextLine(); System.out.println("Insert answer code:")
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
}
这不管用。如何验证每个用户输入?问题在于“使扫描仪超过当前行”。因此,当您在while
条件中调用nextLine()
,并且不保存返回值时,您已经丢失了用户输入的那一行。第3行对nextLine()
的调用返回另一行
你可以试试这样的
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);
}
始终检查scanner.nextLine是否为“退出” }试试:
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
}
不知道有多少是相同的情况,但这对我来说确实有效。不知道到底是什么不适合你。记住只给出“退出”,不要给出它的任何其他案例版本。当询问“不起作用”的事情时,指定它以什么方式不起作用。它的行为与您所期望的有什么不同?在这种情况下,
while(scanner.hasNextLine())
和while(true)
(如Ruchira的回答中)之间有什么不同?while(true)将仅在break和while(scanner.hasNextLine())中终止终止于EOF。但是如果总是有一个扫描仪.nextLine()
(即使是空的)?为什么scanner scanner=new scanner(System.in)
在while循环之外?@drewteriyaki:你不想为每个用户输入创建一个新的扫描仪
。单个系统输入流上的单个扫描仪保持该流上的一致状态。
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
}