Search code examples
javainputmismatchexception

InputMismatchException in LOOP


I tried to find a solution for my problem, but couldn't find one that worked in practice. So please, if YOU'RE NOT SURE you know what the solution is, don't answer. I really need concrete help.

The problem is that when I run my simple code - you can pick a number and it's ok, loop is working fine. When you pick 0, it works too (run is finished), but when you put a letter or any string - there's a problem... an exception keeps looping without stop, even if I try inputting another value.

PS. I need to use Scanner here so please don`t write about readers etc. - just how to solve this specific problem.

Cheers,

Here's code (only main):

public static void main(String[] args) {
    // TODO code application logic here
    Scanner sc = new Scanner(System.in);
    int dane = -1 ;

     boolean keepLooping;   //if you delete this works the same with same problem
do  
{    
    keepLooping = false;
    try
    {

            System.out.println("Pick a number:");
            dane = sc.nextInt();


    }catch (InputMismatchException e)
      {
          System.out.println("Your exception is: " + e);
          keepLooping = false;
      }  
    System.out.println("Out from exception");

}while ((dane != 0)||(keepLooping == true));   

}

Solution

  • Try this:

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        int dane = -1 ;
    
         boolean keepLooping = true;   //if you delete this works the same with same problem
    while(keepLooping && dane != 0)  
    {    
    
        System.out.println("Pick a number:");
    try
    { 
    
            dane = Integer.parseInt(sc.next());
    
    
    }catch (NumberFormatException e)
      {
           keepLooping = true;
      }  
    System.out.println("Out from exception");
    
    }