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

Kur*_*aki 9 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
}
Run Code Online (Sandbox Code Playgroud)

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

Ruc*_*era 10

问题是nextLine() " 推进此扫描程序超过当前行".所以,当你打电话nextLine()while条件,并且不保存返回值,你已经失去了行了用户的输入.nextLine()对第3行的调用返回不同的行.

你可以尝试这样的事情

    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);
    }
Run Code Online (Sandbox Code Playgroud)