【发布时间】:2019-04-01 08:34:49
【问题描述】:
我只是在玩 Java。我试图强制我的程序只接受数字 1 和 2。我相信我已经使用 while 循环成功地做到了这一点(如果我错了,请纠正我)。但是,如果用户输入字符串,我该如何打印错误语句。例如:“abc”。
我的代码:
while (response != 1 && response != 2) {
System.out.println("Please enter 1 for Car or 2 for Van: ");
response = scan.nextInt();
}
if (response == 1) {
vehicleType = VehicleType.CAR;
while (numPassengerSeats < 4 || numPassengerSeats > 7) {
System.out.println("Please enter the number of Passengers: ");
numPassengerSeats = scan.nextInt();
}
} else {
vehicleType = VehicleType.VAN;
while (true) {
System.out.println("Please enter the last maintenance date (dd/mm/yyyy): ");
String formattedDate = scan.next();
lastMaintenanceDate = formatDate(formattedDate);
if (lastMaintenanceDate != null)
break;
}
}
【问题讨论】:
-
java.util.Scanner.nextInt()的API documentation 解释了它在什么情况下会抛出什么异常。如果您输入的不是整数,您将获得InputMismatchException。您必须将nextInt()语句放在 try 块中,然后捕获异常并适当地处理它。
标签: java error-handling