I have this program code. If user enter input in string format such as "Three",i want that program show error message and prompt the user again to enter proper input without rerunning the program. But the program doesn't take input again.
我有这个程序代码。如果用户以字符串格式输入输入,例如“Three”,我希望该程序显示错误消息并再次提示用户输入正确的输入而不重新运行程序。但该计划不再接受输入。
//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));
}
}
The output is like this.
输出是这样的。
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...)
1 个解决方案
#1
1
The wrong input is still in the scanner. Try to do a input.nextLine()
in your catch clause.
扫描仪中仍有错误的输入。尝试在catch子句中执行input.nextLine()。
#1
1
The wrong input is still in the scanner. Try to do a input.nextLine()
in your catch clause.
扫描仪中仍有错误的输入。尝试在catch子句中执行input.nextLine()。