[英]Scanner input validation in while loop
我必須在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
}
這不起作用。 如何驗證每個用戶輸入?
問題是nextLine() “ 推進此掃描程序超過當前行”。 因此,當您在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);
}
嘗試:
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
}
總是檢查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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.