我有这个程序代码。如果用户以字符串格式输入输入,例如“三”,我希望该程序显示错误消息并再次提示用户输入正确的输入,而无需重新运行程序。但是程序不再接受输入。
//Program to get radius form user & calculate area of circle.
import java.util.InputMismatchException;
import java.util.Scanner;
public class AreaOfCircle {
public static void main(String[] args) {
final float PI=3.14f;
double rad=0.0;
Scanner input=new Scanner(System.in);
while(true){
try {
System.out.println("Enter radius of circle: ");
rad = input.nextDouble();
break;
}
catch (InputMismatchException e) {
System.out.println("Please enter radius in proper format");
}
}
System.out.println("Area of circle is: "+(PI*rad*rad));
}
}
输出是这样的。
Enter radius of circle:
Three
Please enter radius in proper format
Enter radius of circle:
Please enter radius in proper format
Enter radius of circle:
Please enter radius in proper format
Enter radius of circle:
Please enter radius in proper format
(infitely...)