0

I've got a very simple problem (i'm starting Java), but for some reason, I cannot find a decent answer. I'm making a program, and the user has to make a choice and an input. But I need to do some checking for valid input, and if he inputs a char instead of an int, I need to give him an error message.

The code is:

Scanner n = new Scanner (System.in);
System.out.print("...");
    sp = n.nextInt();
    if ( sp != 1 )
    {
        if ( sp == 2 )
        {
            System.out.println("...");

        }
    }
    else 
        System.out.println("...");

    **//and here the error message shoub be,** 
    **//in case the user inputs something different than a int**
David S.
  • 9,721
  • 9
  • 53
  • 95
CH4B
  • 37
  • 5
  • So what is it doing so far? What’s your problem? Please specify. – Jacob B. Jun 12 '18 at 20:06
  • try/catch exception handling is what you want here – smoggers Jun 12 '18 at 20:07
  • Additionally, please try to clean up your code to show us the minimum example of what you have working so far and where the problem is. Also, explain exactly what you want to accomplish and what you have tried so far. – fhorrobin Jun 12 '18 at 20:08
  • You're looking for this https://stackoverflow.com/questions/5287538/how-can-i-get-the-user-input-in-java, MarredCheese answer has a try catch aswell. – namokarm Jun 12 '18 at 20:09
  • There is a good answer here explaining many applications of Scanner for input checking: https://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner – fhorrobin Jun 12 '18 at 20:10

2 Answers2

0

have you tried using Java's try....catch statements. I suggest you wrap your code like this:

try{
       //put your code here
} catch(e){
       System.out.println(e.message)
}

You can research more about handling IO errors and put some extra guard in your code. Hope this helps!

Dalton Whyte
  • 537
  • 5
  • 15
0

You probably need to add try catch like this... It should work fine... if the user will now enter a string it will throw an exception and the catch block will work

Scanner n = new Scanner (System.in);
System.out.print("..."); 
try{
    sp = n.nextInt();
} catch(Exception e){
       //Display your message here
}
if ( sp != 1 ) { 
    if ( sp == 2 ) { 
        System.out.println("...");
    } 
} else 
       System.out.println("...");