9

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

      }
  }
jjkk0990
  • 93
  • 1
  • 1
  • 4

7 Answers7

18

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");
}
Pandiyan Cool
  • 6,381
  • 8
  • 51
  • 87
6
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;
  }
Rajendra_Prasad
  • 1,300
  • 4
  • 18
  • 36
  • I tried !sc.hasNextInt() but it's giving errors. I'll edit the first post – jjkk0990 Aug 08 '13 at 06:45
  • In your first if condition you are trying to read integer value this is what is causing that error,because how can you read integer when you have entered that if statement which satisfies only if your input is not integer please check your updated code(first if condition part) – Rajendra_Prasad Aug 08 '13 at 07:09
2

you have following errors which in turn is causing you that exception, let me explain it

this is your existing code:

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

in the above code if(!scan.hasNextInt()) will become true only when user input contains both characters as well as integers like your input adfd 123.

but you are trying to read only integers inside the if condition using usrInput= sc.nextInt();. Which is incorrect,that's what is throwing Exception in thread "main" java.util.InputMismatchException.

so correct code should be

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

in the above code sc.next() will help to read new input from user and continue will help in executing same if condition(i.e if(!scan.hasNextInt())) again.

Please use code in my first answer to build your complete logic.let me know if you need any explanation on it.

Rajendra_Prasad
  • 1,300
  • 4
  • 18
  • 36
  • Hi, thanks for answering. It doesn't work, unless there's something I'm not seeing. I'll update my post again. – jjkk0990 Aug 08 '13 at 11:42
2

try this code [updated]:

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;
            } 
        }
Rajendra_Prasad
  • 1,300
  • 4
  • 18
  • 36
  • is there a reason why you put it in a for(;;) loop? – jjkk0990 Aug 08 '13 at 12:07
  • yes,It is an infinite loop,It is required to keep looping again and again until user enters correct input.once user enters correct input the loop will break – Rajendra_Prasad Aug 08 '13 at 12:16
  • I tried that but it's not stopping the loop and it doesn't ask me to input another integer. Can I do a while loop? E.g while(!error)... – jjkk0990 Aug 08 '13 at 12:24
  • yes i knew it i was just checking whether you are putting any effort to solve your problem.Anyway try my updated code. – Rajendra_Prasad Aug 08 '13 at 12:32
  • that infinite loop doesn't work for me. I updated my code with a while loop but it's also not working and giving the same errors. Can you take a look? – jjkk0990 Aug 08 '13 at 12:34
  • i have updated my code its working,try this it gonna work for you also and don't forget to accept the answer. – Rajendra_Prasad Aug 08 '13 at 12:41
0

Taken from a 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;
}
Community
  • 1
  • 1
ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64
0

Maybe you can try this:

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;
}
Community
  • 1
  • 1
shady
  • 455
  • 1
  • 7
  • 18
0

This is to keep requesting inputs while this input is integer and find whether it is odd or even else it will end.

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