【问题标题】:How to check if user input is not an int value如何检查用户输入是否不是 int 值
【发布时间】:2013-08-08 06:23:41
【问题描述】:

我需要检查用户输入的值是否不是 int 值。我尝试了我所知道的不同组合,但我没有得到任何信息或随机错误

例如:

如果用户输入“adfadf 1324”,它会发出警告消息。


我有什么:

       // Initialize a Scanner to read input from the command line
       Scanner sc = new Scanner(System.in);
       int integer, smallest = 0, input;
       boolean error = false;

       System.out.print("Enter an integer between 1-100: ");
       range = sc.nextInt();

       if(!sc.hasNextInt()) {

          error = true;
          System.out.println("Invalid input!");
          System.out.print("How many integers shall we compare? (Enter an integer between 1-100: ");
          sc.next();
    }

       while(error) {
          for(int ii = 1; ii <= integer; ii++) {

              ...

          } // end for loop
      }
      System.out.println("The smallest number entered was: " + smallest);

      }
  }

【问题讨论】:

  • 是通过异常实现的唯一方法吗?因为我需要检查它是否大于 1 以及它是否是一个 int 值。或者也可以在例外情况下这样做?
  • 你检查过我的代码吗?
  • 查看我更新的代码,它肯定会工作
  • 你试过我更新的代码了吗???

标签: java validation


【解决方案1】:

如果输入无效,只需抛出异常

Scanner sc=new Scanner(System.in);
try
{
  System.out.println("Please input an integer");
  //nextInt will throw InputMismatchException
  //if the next token does not match the Integer
  //regular expression, or is out of range
  int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
  //Print "This is not an integer"
  //when user put other than integer
  System.out.println("This is not an integer");
}

【讨论】:

  • @rashedazad 我的荣幸
【解决方案2】:
Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

【讨论】:

  • 我试过 !sc.hasNextInt() 但它给出了错误。我将编辑第一篇文章
  • 在您的第一个 if 条件中,您尝试读取整数值,这是导致该错误的原因,因为当您输入仅当您的输入不是整数时才满足的 if 语句时,您如何读取整数请检查您更新的代码(第一个 if 条件部分)
【解决方案3】:

您有以下错误导致您出现该异常,让我解释一下

这是您现有的代码:

if(!scan.hasNextInt()) {
        System.out.println("Invalid input!");
        System.out.print("Enter an integer: ");
        usrInput= sc.nextInt();
    }

在上面的代码中,if(!scan.hasNextInt()) 将变为true,仅当用户输入包含字符和整数,如您的输入adfd 123

但您尝试使用usrInput= sc.nextInt(); 仅读取 if 条件内的整数。这是不正确的,这就是抛出Exception in thread "main" java.util.InputMismatchException

所以正确的代码应该是

 if(!scan.hasNextInt()) {
            System.out.println("Invalid input!");
            System.out.print("Enter an integer: ");
            sc.next(); 
            continue;
        }

在上面的代码中,sc.next() 将有助于读取用户的新输入,continue 将有助于再次执行相同的 if 条件(i.e if(!scan.hasNextInt()))。

请在我的第一个答案中使用代码来构建您的完整逻辑。如果您需要任何解释,请告诉我。

【讨论】:

  • 您好,感谢您的回答。它不起作用,除非有我没有看到的东西。我会再次更新我的帖子。
【解决方案4】:

试试这个代码[更新]

Scanner scan = null;
       int range, smallest = 0, input;

     for(;;){
         boolean error=false;
        scan = new Scanner(System.in);
        System.out.print("Enter an integer between 1-100:  ");


            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!");                      
                continue;
            }
         range = scan.nextInt();
            if(range < 1) {
                System.out.println("Invalid input!");
                error=true;
            }
        if(error)
        {
        //do nothing
        }
        else
        {
       break;
        }

        }
             for(int ii = 1; ii <= range; ii++) {
            scan = new Scanner(System.in);
            System.out.print("Enter value " + ii + ": ");

            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!"); 
               ii--;
                continue;
            } 
        }

【讨论】:

  • 你把它放在 for(;;) 循环中是有原因的吗?
  • 是的,这是一个无限循环,需要不断循环,直到用户输入正确的输入。一旦用户输入正确的输入,循环就会中断
  • 我试过了,但它并没有停止循环,也没有要求我输入另一个整数。我可以做一个while循环吗?例如 while(!error)...
  • 是的,我知道我只是在检查您是否正在努力解决您的问题。无论如何尝试我更新的代码。
  • 那个无限循环对我不起作用。我用一个while循环更新了我的代码,但它也不起作用并给出了同样的错误。可以看看吗?
【解决方案5】:

取自related post

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    // only got here if we didn't return false
    return true;
}

【讨论】:

    【解决方案6】:

    也许你可以试试这个:

    int function(){
    Scanner input = new Scanner(System.in);   
    System.out.print("Enter an integer between 1-100: ");   
    int range;
    while(true){   
        if(input.hasNextInt()){   
        range = input.nextInt();
        if(0<=range && range <= 100)
            break;
        else
            continue;
        }
        input.nextLine();  //Comsume the garbage value
        System.out.println("Enter an integer between 1-100:");
    }
    return range;
    }
    

    【讨论】:

      【解决方案7】:

      这是为了在此输入为整数时继续请求输入,并查找它是奇数还是偶数,否则它将结束。

      int counter = 1;
          System.out.println("Enter a number:");
          Scanner OddInput = new Scanner(System.in);
              while(OddInput.hasNextInt()){
                  int Num = OddInput.nextInt();
                  if (Num %2==0){
                      System.out.println("Number " + Num + " is Even");
                      System.out.println("Enter a number:");
                  }
                  else {
                      System.out.println("Number " + Num + " is Odd");
                      System.out.println("Enter a number:");
                      }
                  }
              System.out.println("Program Ended");
          }
      

      【讨论】:

        猜你喜欢
        • 2017-05-22
        • 2012-08-17
        • 1970-01-01
        • 1970-01-01
        • 2018-05-08
        • 2013-01-06
        • 2018-04-14
        • 2017-07-19
        • 2018-09-08
        相关资源
        最近更新 更多