Java中LocalTime构建时int类型时分格式问题求助
解决方案
核心问题
你用int接收的小时/分钟,拼接成字符串后会丢失前导零,比如9变成"9",导致生成"10:9"这种不符合LocalTime要求的格式(必须是两位数字,比如"10:09"),所以parse方法报错。
两种可行方案
方案1:用String.format补全前导零再解析
保留int类型接收输入,用String.format把数字格式化为两位带前导零的字符串,再生成符合要求的时间字符串传给LocalTime.parse:
int hours; int minutes; Scanner scan = new Scanner(System.in); System.out.println("Input a number for the hours (00-23): "); hours = scan.nextInt(); System.out.println("Input a number for the minutes (00-59): "); minutes = scan.nextInt(); // 用%02d格式化为两位数字,自动补前导零 String timeStr = String.format("%02d:%02d", hours, minutes); LocalTime result = LocalTime.parse(timeStr); System.out.println(result);
方案2:直接用LocalTime.of构建(更推荐)
完全不需要转字符串,LocalTime本身就提供了直接接收int类型小时和分钟的静态方法of,这是最简洁的方式:
int hours; int minutes; Scanner scan = new Scanner(System.in); System.out.println("Input a number for the hours (00-23): "); hours = scan.nextInt(); System.out.println("Input a number for the minutes (00-59): "); minutes = scan.nextInt(); // 直接用int参数构建LocalTime,无需字符串转换 LocalTime result = LocalTime.of(hours, minutes); System.out.println(result);
关于你尝试过的方法说明
NumberFormat是抽象类,确实不能直接实例化,你可以用它的子类DecimalFormat来格式化数字,但其实对于这个场景来说完全没必要,上面两种方案更简单。String.format的%02d表示:以两位数字格式输出,不足两位时用0补全前导,正好满足时间格式的要求。
内容的提问来源于stack exchange,提问作者Daleo dorito
相关产品推荐
相关产品推荐

