【问题标题】:Scanner input validation in while loopwhile循环中的扫描仪输入验证
【发布时间】:2013-11-25 20:57:24
【问题描述】:

我必须在 while 循环中显示扫描仪输入:用户必须插入输入,直到他写“退出”。所以,我必须验证每个输入以检查他是否写了“退出”。我该怎么做?

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
}

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

【问题讨论】:

  • 不确定有多少相同的情况,但这实际上对我来说很有效。不知道到底什么不适合你。请记住只给出“退出”,而不是它的任何其他案例版本。
  • 当询问“不起作用”的东西时,请说明它不起作用的方式。它的行为与您的预期有何不同?

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


【解决方案1】:

问题在于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);
    }

【讨论】:

  • 为什么Scanner scanner = new Scanner(System.in)在while循环之外?
  • @drewteriyaki:您不希望为每个用户输入创建一个新的Scanner。单个系统输入流上的单个 Scanner 在该流上保持一致的状态。
【解决方案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
}

【讨论】:

  • 在这种情况下,while (scanner.hasNextLine())while (true)(如 Ruchira 的回答)有什么区别?
  • while(true) 将仅在 break 处终止,而 while(scanner.hasNextLine()) 在 EOF 处终止。
  • 但是如果总是有scanner.nextLine()(即使是空的),它怎么能到达文件末尾呢?
【解决方案3】:

总是检查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 

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多