Java自定义DateTimeFormatter解析yyyy-MM-dd-HH串转LocalDateTime报错问题
问题修复方案
错误根因
本次报错和DateTimeFormatter的日期格式定义无关,是Scanner输入读取逻辑导致的问题:
- Scanner的
nextInt()、next()这类方法只会读取对应类型的有效内容,不会消费输入末尾的换行符 - 执行完
duurtijd = sc.nextInt()后,输入缓冲区里残留了用户输入完时长按下的换行符 - 后续执行
wanneer = sc.nextLine()时,会直接读取到这个残留的换行符,返回空字符串,最终触发空串解析异常
修复方案
任选以下一种方式即可解决:
方式1:主动消费残留换行符
在最后一次nextInt()调用后加一行sc.nextLine()吃掉残留的换行,再读取日期输入:
System.out.println("Wat is de duurtijd van een optreden (in minuten)?"); duurtijd = sc.nextInt(); // 新增下面这行,消费nextInt残留的换行符 sc.nextLine(); System.out.println("Wanneer zal je festival doorgaan? geef de startdatum als volgt: jaar-maand-dag-uur"); wanneer = sc.nextLine();
方式2:统一用nextLine读取所有输入
避免不同读取方法混用导致的缓冲区残留问题,所有输入都用nextLine()读取后自行做类型转换:
System.out.println("Wat is de naam van je festival?"); naam = sc.nextLine(); System.out.println("Hoeveel dagen duurt je festival?"); dagen = Integer.parseInt(sc.nextLine()); System.out.println("Hoeveel artiesten plan je per dag?"); artiesten = Integer.parseInt(sc.nextLine()); System.out.println("Wat is de duurtijd van een optreden (in minuten)?"); duurtijd = Integer.parseInt(sc.nextLine()); System.out.println("Wanneer zal je festival doorgaan? geef de startdatum als volgt: jaar-maand-dag-uur"); wanneer = sc.nextLine();
额外优化建议
可以在解析前增加输入合法性校验,避免用户误输入空值触发报错:
if (wanneer == null || wanneer.isBlank()) { System.out.println("输入的日期不能为空,请重新输入"); // 可自行补充重新输入的循环逻辑 } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH"); LocalDateTime formatDateTime = LocalDateTime.parse(wanneer, formatter);
内容的提问来源于stack exchange,提问作者Loran Maes
相关产品推荐
相关产品推荐

