Java预约程序InputMismatchException异常处理新手咨询
解决你的预约程序异常处理问题
嗨,作为编程新手能想到用异常处理来解决输入问题已经很棒了!我帮你梳理下代码里的问题,以及如何正确处理非整数输入的情况:
首先,你的代码存在的核心问题
你在try块外面已经调用了input.nextInt(),这时候如果用户输入的不是整数,这个外部的nextInt()就会直接抛出InputMismatchException,根本不会进入try块,所以你的catch块完全起不到作用。这是当前代码最关键的问题。
关于异常类型的疑问:InputMismatchException是正确的选择
你完全选对了!当Scanner的nextInt()方法无法将用户输入解析为整数类型(比如输入字符串、浮点数、符号等)时,就会抛出InputMismatchException,这正是你需要捕获的异常类型,不用考虑其他异常~
修正后的完整代码
下面是调整后的代码,我会在注释里说明关键修改点:
import java.util.InputMismatchException; import java.util.Scanner; // 假设appointments数组和name、apTotal变量已经提前定义好 public class AppointmentBooking { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name = "TestUser"; // 示例用户名,可替换为实际获取的用户名 String[] appointments = new String[7]; // 索引0不用,1-6对应时段 int apTotal = 0; boolean created = false; while (!created) { System.out.println("When would you like your appointment? (Enter integer 1-6)"); int userTime = -1; // 初始化一个无效值,避免未赋值报错 try { // 把输入操作放到try块内,这样异常会被正确捕获 userTime = input.nextInt(); // 先检查输入范围是否合法 if (userTime < 1 || userTime > 6) { System.out.println("Time value not in range! Please enter a number between 1 and 6."); continue; // 跳过后续检查,回到循环开头重新输入 } // 检查当前时段是否已被占用 if (appointments[userTime] != null) { System.out.println("Time already taken! Choose another slot."); } else { // 成功完成预约 created = true; apTotal++; appointments[userTime] = name; System.out.println("Appointment booked successfully at slot " + userTime); } } catch (InputMismatchException ime) { System.out.println("Error! Please enter an integer from 1 to 6. Letters and symbols are not allowed."); // 关键操作:清理Scanner的缓冲区,避免错误输入残留导致无限循环 input.nextLine(); } } input.close(); } }
关键修改说明
- 将输入操作移入try块:这样当输入非整数时,异常会被
catch块捕获,而不是提前触发程序崩溃。 - 添加
input.nextLine()清理缓冲区:当抛出InputMismatchException时,错误的输入内容还留在Scanner的缓冲区里,如果不清理,下一次循环调用nextInt()会再次读取到同样的错误输入,导致无限循环。 - 调整逻辑顺序:先检查输入范围,再检查时段是否被占用,逻辑更清晰,用户能更及时得到对应反馈。
- 初始化
userTime为无效值:避免出现变量未赋值就被使用的编译问题。
这样调整后,你的程序就能正确处理各种非整数输入,并且友好提示用户重新输入啦!
内容的提问来源于stack exchange,提问作者Arush Kumar
相关产品推荐
相关产品推荐

