-2

I got this lines :

    while(flag==0){

    try{
        code=input.nextInt();
    }
    catch(java.util.InputMismatchException z)
    {
        System.out.print("\nDigito(s) Invalidos!\n");
        flag=1;
    }
    finally
    {
       if(flag==1)
       flag=0;
       else{flag=1;}

    }
}

But the input.nextInt() only works at the first time. What's the best way to prevent the user to insert a char on an Integer?

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
Escaga Seen
  • 131
  • 11
  • 2
    What are you trying to do with that bizarre `finally` block? Just use `break` instead of using `flag` at all. – Andy Turner Dec 29 '17 at 00:50
  • 1
    `char` is a subset of `int`. If you don't want your user to put bogus values in, then read them all in as a `String` instead and then parse out integer values from that. – Makoto Dec 29 '17 at 00:54

1 Answers1

1

No need for flag or finally block in your case, you just can break the loop in catch block, You can do the following :

        while(true){
            try{
                code=input.nextInt();
            }
            catch(java.util.InputMismatchException z)
            {
                System.out.print("\nDigito(s) Invalidos!\n");
                break;
            }
        }
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39