while循环中的扫描仪输入验证

时间:2013-11-13 10:00:55

标签: java loops while-loop java.util.scanner

我必须在 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
}

这不起作用。如何验证每个用户输入?

3 个答案:

答案 0 :(得分:10)

问题是nextLine()“推进此扫描程序超过当前行”。因此,当您在nextLine()条件中调用while并且不保存返回值时,您已经丢失了用户输入的那一行。第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);
    }

答案 1 :(得分:2)

尝试:

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
}

答案 2 :(得分:0)

始终检查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 

}