Java中用split拆分时间计算总秒数,如何适配无小时段的mm:ss输入
适配mm:ss格式的时长转秒数实现
原代码核心问题
- 原实现默认
split(":")后固定返回3个元素,仅能处理HH:mm:ss格式输入 - 当用户输入mm:ss格式时,拆分后数组长度仅为2,访问
split[2]会直接触发ArrayIndexOutOfBoundsException
适配实现逻辑
- 先对输入做
trim()处理,过滤前后多余空格,避免解析异常 - 校验拆分后的数组长度,仅支持1~3段的合法输入,非法段数直接输出提示退出
- 采用从右往左的取值规则:最右侧段固定为秒,往左依次为分钟、小时,完全匹配两类格式的计算要求,无需为mm:ss格式手动补前导小时位
完整修改后代码
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int seconds = 0; System.out.println("Enter time in HH:mm:ss or mm:ss to convert into seconds:"); String timeInput = scan.nextLine().trim(); scan.close(); String[] split = timeInput.split(":"); int splitLen = split.length; // 限制支持的格式段数,避免非法输入导致异常 if (splitLen < 1 || splitLen > 3) { System.out.println("Invalid time format. Please input as HH:mm:ss or mm:ss."); return; } int currentIndex = splitLen - 1; // 最右段为秒位 seconds += Integer.parseInt(split[currentIndex]); if (splitLen >= 2) { currentIndex--; // 倒数第二段为分钟位 seconds += Integer.parseInt(split[currentIndex]) * 60; } if (splitLen == 3) { currentIndex--; // 倒数第三段为小时位 seconds += Integer.parseInt(split[currentIndex]) * 3600; } System.out.println(seconds); } }
测试验证效果
- 输入
3:42→ 输出222,与输入0:3:42的计算结果完全一致 - 输入
1:02:03→ 输出3723 - 输入
45→ 输出45,额外兼容纯秒数输入场景
内容的提问来源于stack exchange,提问作者Idiot With a Uke
相关产品推荐
相关产品推荐

