Scanner input validation in while loop

◇◆丶佛笑我妖孽 提交于 2019-11-26 10:02:09

问题


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?


回答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);
    }



回答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
}



回答3:


always check if scanner.nextLine is not "quit"

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 

}



来源:https://stackoverflow.com/questions/19950713/scanner-input-validation-in-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!