Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if user input is not an int value

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

For example:

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


What I have:

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

      }
  }
like image 348
jjkk0990 Avatar asked Aug 08 '13 06:08

jjkk0990


2 Answers

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");
}
like image 181
Pandiyan Cool Avatar answered Oct 19 '22 19:10

Pandiyan Cool


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;
  }
like image 38
Rajendra_Prasad Avatar answered Oct 19 '22 21:10

Rajendra_Prasad