My program has an endless loop, when I use try and catch block in a while loop.
import java.util.*;
class Try
{
public
The problem is that when you call nextInt you will screw the Scanner and so it cannot be used once nextInt caused in exception. That Scanner is not valid anymore. To get around this, you should read the content as string and cast it, when the cast operation fails, you don't have to worry about anything.
I would do it like this:
import java.util.*;
class Try
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
while(true)
{
try{
System.out.println("Enter a no ");
int s=Integer.parseInt(sc.next()); // or sc.nextLine() if you wish to get multi digit numbers
}catch(Exception e)
{
System.out.println("Invalid input try again");
}
}
}
}