while循环中的扫描仪输入验证 [英] Scanner input validation in while loop

查看:105
本文介绍了while循环中的扫描仪输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在 while 循环中显示Scanner输入:用户必须插入输入,直到他写退出。所以,我必须验证每个输入以检查他是否写退出。我怎么能这样做?

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?

推荐答案

问题是 nextLine()使此扫描器超过当前行。所以当你在中调用 nextLine()条件,并且不保存返回值时,你已经丢失了用户输入的那一行。第3行对 nextLine()的调用返回不同的行。

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.

你可以尝试这样的事情

    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循环中的扫描仪输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆