You need to enable JavaScript to run this app. Java中用split拆分时间计算总秒数,如何适配无小时段的mm:ss输入
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.07 14:54:10