java - Endless loop while using "try and catch " block inside a "while loop" -


my program has endless loop, when use try , catch block in while loop.

import java.util.*; class try {     public static void main(string args[])     {         scanner sc=new scanner(system.in);         while(true)         {             try {                 system.out.println("enter no ");                 int s=sc.nextint();             } catch(exception e) {                 system.out.println("invalid input try again");             }         }     } } 

when input integer, runs fine , asks input, when input char, goes endless loop. why so?

your program enters infinite loop when invalid input encountered because nextint() not consume invalid tokens. whatever token caused exception stay there , keep causing exception thrown next time try use nextint().

this can solved putting nextline() call inside catch block consume whatever input causing exception thrown, clearing input stream , allowing user continue trying.


Comments