本文介绍了如何检查用户输入是否不是int值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to check if a user input value is not an int value. I've tried different combinations of what I know but I either get nothing or random errors

例如:

如果用户输入adfadf 1324,它将发出警告信息。

If the user inputs "adfadf 1324" it'll raise a warning message.

我所拥有的:

       // 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);

      }
  }


推荐答案

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

Simply throw Exception if input is invalid

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");
}

这篇关于如何检查用户输入是否不是int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:31