Java停车场系统时间格式化问题:如何将6:0显示为06:00
停车场时间格式化与时间处理逻辑问题
问题描述
开发停车场车辆停放时间显示功能时遇到两个问题:
- 输入
hh:mm格式的时间后,通过split拆分转成整数输出,会显示类似Car with license aaaaaa parked at 6:0的内容,需要调整为06:00的两位补零格式; - 确认当前用数组拆分小时和分钟的方式是否正确,后续还要处理车辆离场及按分钟计费的逻辑。
当前代码片段:
public static void main(String[] args) { String code = " "; String sentinel = "Q"; Stack<Vehicle> parkingLot = new Stack<>(); ArrayList<Vehicle> temporarilyParking = new ArrayList<>(); Scanner scan = new Scanner (System.in); while(!code.equalsIgnoreCase(sentinel)) { System.out.print("Enter code (A for Arrival, D for Departure, Q to quit): "); code = scan.nextLine(); switch(code.toUpperCase()) { case "A": System.out.print("Enter license : "); String license = scan.nextLine(); System.out.print("Enter time (hh:mm):"); String time = scan.nextLine(); String []timeArray; timeArray = time.split(":"); int hour = Integer.parseInt(timeArray[0]); int minutes = Integer.parseInt(timeArray[1]); System.out.println("Car with license " + license + " parked at " + hour + ":" + minutes); break; } } }
解决方案
1. 时间格式化输出
Java中可以用String.format方法实现两位补零的格式化,把输出语句替换为:
System.out.println("Car with license " + license + " parked at " + String.format("%02d:%02d", hour, minutes));
%02d表示将整数格式化为两位,不足两位时前面补0,这样就能输出06:00的标准格式。
2. 时间拆分方式的正确性与优化
- 拆分方式的正确性:用
split(":")拆分hh:mm格式的字符串是可行的,但要注意输入合法性问题——如果用户输入的时间格式错误(比如没有冒号、包含非数字字符),会抛出NumberFormatException或ArrayIndexOutOfBoundsException。建议添加格式校验,比如用正则表达式先验证输入:if (!time.matches("^\\d{1,2}:\\d{1,2}$")) { System.out.println("请输入正确的hh:mm格式时间"); break; } - 后续计费逻辑优化:为了方便计算停放时长,建议将时间转换成总分钟数存储,比如:
车辆离场时,同样把离场时间转成总分钟数,两者相减就能得到停放的总分钟数,直接用于计费计算,逻辑更简洁不易出错。int totalParkMinutes = hour * 60 + minutes;
修改后的完整代码示例(包含格式化和总分钟数存储):
public static void main(String[] args) { String code = " "; String sentinel = "Q"; Stack<Vehicle> parkingLot = new Stack<>(); ArrayList<Vehicle> temporarilyParking = new ArrayList<>(); Scanner scan = new Scanner (System.in); while(!code.equalsIgnoreCase(sentinel)) { System.out.print("Enter code (A for Arrival, D for Departure, Q to quit): "); code = scan.nextLine(); switch(code.toUpperCase()) { case "A": System.out.print("Enter license : "); String license = scan.nextLine(); System.out.print("Enter time (hh:mm):"); String time = scan.nextLine(); // 时间格式校验 if (!time.matches("^\\d{1,2}:\\d{1,2}$")) { System.out.println("请输入正确的hh:mm格式时间"); break; } String []timeArray = time.split(":"); int hour = Integer.parseInt(timeArray[0]); int minutes = Integer.parseInt(timeArray[1]); // 转换为总分钟数,方便后续计算 int totalParkMinutes = hour * 60 + minutes; // 格式化输出时间 System.out.println("Car with license " + license + " parked at " + String.format("%02d:%02d", hour, minutes)); break; } } }
内容的提问来源于stack exchange,提问作者Down25
相关产品推荐
相关产品推荐

