在 catch block 中,我试图纠正用户输入错误的问题。测试时,如果我使用“break”关键字,它不会跳转到最初的问题。如果我使用“继续”,它会无限循环。 "Sc.next();"似乎也没有解决它。
这是代码的相关部分。
public class ComputerAge {
private static int age;
private static int year;
private static int month;
private static int date;
private static Calendar birthdate;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the numeral representing your birth month: ");
do {
try {
month = sc.nextInt();
} catch (InputMismatchException ime){
System.out.println("Your respone must be a whole number");
break;
}
} while (!sc.hasNextInt());
最佳答案
为了解决问题,我们应该确定最后要完成什么。
我们希望月份是数字月份,即数字 > 0。
因此:
- 如果用户填写了正确的数字,
month
将被填写。 - 否则,将抛出异常并且
month
将保持为“0”。
结论:我们希望我们的程序在月份等于 0 时继续运行。
解决方案非常简单:
虽然条件应该是:
while (month == 0);
并且您应该将 break
更改为 sc.next()
。
关于java - 循环做...虽然不确定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275790/