try
{
System.out.println("Enter your name");
Name = in.next();
}
catch (InputMismatchException exception) {
System.out.println("Enter valid input");
}
当用户输入整数值时,我需要暂停执行,然后需要显示"输入有效输入"并再次不得不重新尝试我的尝试块。我怎样才能在java中实现这一点..
答案 0 :(得分:2)
试试这个:
while(true)
{
try
{
System.out.println("Enter your name");
Name = in.next();
break;
}
catch (InputMismatchException exception) {
System.out.println("Enter valid input");
}
in.next();
continue;
}
答案 1 :(得分:0)
int flag=0;
do{
try
{
System.out.println("Enter your name");
Name = in.next();
int num=Integer.parseInt(Name);//this line will generate exception if entered input is not integer
}
catch (InputMismatchException exception) {
System.out.println("Enter valid input");
flag=1;//only run if the Numberformatexception is generated(i.e integer was not entered)
}
}while(flag==0);