My program has an endless loop, when I use try and catch block in a 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 a no ");
int s=sc.nextInt();
} catch(Exception e) {
System.out.println("Invalid input try again");
}
}
}
}
When I input an integer, it runs fine and asks for another input, but when I input a char, it goes for endless loop. Why is this so?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…