Java日期输入程序捕获InputMismatchException后无法重新输入的问题求助
解决日期输入验证程序异常后无法重新输入的问题
原代码的核心问题
- 循环依赖
count变量控制次数,初始值为1,仅执行一次循环后count变为0,循环直接终止,无法实现重新输入。 - 当输入的日期数值非法(如day不在1-31)时,
continue会跳转到循环末尾,导致count递减,同样会提前结束循环。 - 异常捕获后,仅清空了当前错误输入,但循环次数已耗尽,无法触发新一轮输入流程。
修改后的代码
import java.util.*; public class P3 { public static void main(String[] args) { int day = 0, month = 0, year = 0; Scanner sc = new Scanner(System.in); boolean isValidInput = false; do { System.out.println("============================================="); System.out.println("Enter (DD-MM-YYYY)"); try { // Day Part System.out.print(" DD: "); day = sc.nextInt(); if (day < 1 || day > 31) { System.out.println("invalid day [range:1-31]\nEnter Again"); // 清空Scanner中可能残留的无效输入 sc.nextLine(); continue; } // Month Part System.out.print(" MM: "); month = sc.nextInt(); if (month < 1 || month > 12) { System.out.println("invalid month [range:1-12]\nEnter Again"); sc.nextLine(); continue; } // Year Part System.out.print(" YYYY: "); year = sc.nextInt(); if (year < 1900) { System.out.println("no support for year less than 1900 [range:1900-current]"); sc.nextLine(); continue; } // 所有输入验证通过 System.out.println("Day: " + day + " Month: " + month + " Year: " + year); System.out.println("============================================="); isValidInput = true; } catch (InputMismatchException e) { System.out.println("You entered wrong input, please enter numbers only"); // 清空错误的非数字输入,避免死循环 sc.nextLine(); } } while (!isValidInput); sc.close(); } }
关键修改说明
- 用
isValidInput布尔变量控制循环,只有当所有输入验证通过时才将其设为true,终止循环,实现无限重试直到输入有效。 - 在数值非法的
if判断后,添加sc.nextLine()清空Scanner缓存,避免残留的换行符或无效输入影响下一次读取。 - 移除了原来的
count变量,解决了循环次数受限的问题。 - 异常捕获后,使用
sc.nextLine()清空整个错误输入行,而不是sc.next()(sc.next()只会读取到空格,若输入是带空格的无效内容会残留)。 - 修正了原代码中"less then"的拼写错误为"less than"。
内容的提问来源于stack exchange,提问作者Lord_Shiva_Mahadev
相关产品推荐
相关产品推荐

