【问题标题】:How to prompt a user using scan.nextInt for int type in a while loop?如何在 while 循环中使用 scan.nextInt 提示用户 int 类型?
【发布时间】:2012-12-09 17:54:49
【问题描述】:
System.out.println("How long is the word you would like to guess?");
    while (goodInput==false)
            {
                try
                {
                    wordSize=scan.nextInt();
                    goodInput=true;
                }
                catch(InputMismatchException ime)
                {
                    System.out.println("Thats not a number! Try again");
                }
            }

输入错误类型后,控制台在无限循环中重复“那不是数字...”。

*编辑

我试过了

while(goodInput==false)
        {
            if (scan.hasNextInt())
            {
                wordSize=scan.nextInt();
                goodInput=true;
            }
            else
            {
                System.out.println("Thats not a number! Try again");
            }
        }

也会产生同样的错误

【问题讨论】:

  • 你应该使用scan.hasNextInt() 方法而不是捕获异常。
  • wordSize的类型是什么?
  • @Fyre 假设代码可以编译,它只能是intInteger
  • 您可能需要在 .nextint 之后使用 .nextline 方法读取下一行字符

标签: java exception-handling java.util.scanner


【解决方案1】:

如果提供了非整数,则永远不会消耗输入,因此输入会一次又一次地传递,从而导致无限循环。您可以使用:

scan.nextLine();

在您的异常块中,但更好用:

while (scan.hasNextInt() && !goodInput) {

【讨论】:

    【解决方案2】:
     while (goodInput==false) {
          System.out.println("How long is the word you would like to guess?");
          if (scan.hasNextInt()) {
            wordSize=scan.nextInt();
            goodInput=true;
          }
          else scan.next();
      }
    

    【讨论】:

    • 谢谢,问题刚刚得到解答。
    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2019-10-30
    • 2019-08-03
    • 1970-01-01
    相关资源
    最近更新 更多