java - 如果输入满足要求的条件,为什么 if 语句会被忽略?

标签 java string

我正在生成一个代码,该代码采用用户的 AM/PM 格式并以 24 小时格式提供输出。该程序适用于所有输入,除了输入时间范围在“12:00:00 AM”到“12:00:00 PM”(不包括)之间时。

    String[] time = s.split(":");
    int hours = Integer.parseInt(time[0]);
    int minutes = Integer.parseInt(time[1]);
    if(s.endsWith("AM")){
        time[2] = time[2].replace("AM","");
    }
    if(s.endsWith("PM")){
        time[2] = time[2].replace("PM","");
        if(hours != 12)hours+=12;
    }
    int seconds = Integer.parseInt(time[2]);

    String hh,mm,ss;
    if(hours < 10 && s.endsWith("AM")){
        hh = "0"+Integer.toString(hours);
    }
    if(hours == 12 && s.endsWith("AM")){
        hh = "00";
    }else{
        hh = Integer.toString(hours);
    }

每当我输入 6:05:30 AM 时,hh 都会返回字符串“6”,但同时 PM 格式的时间会返回“06”。

最佳答案

为了回答您的问题,您在最后一个 if 语句 block 中省略了 else 语句:

if(hours < 10 && s.endsWith("AM")){
    hh = "0"+Integer.toString(hours);
}
else // This one
if(hours == 12 && s.endsWith("AM")){
    hh = "00";
}else{
    hh = Integer.toString(hours);
}

关于java - 如果输入满足要求的条件,为什么 if 语句会被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45616964/

相关文章:

javascript - 验证整个字符串并获取所有匹配项

c++ - strlen vs停止为零的字符串操作的性能

python - 如何只替换子字符串而不替换整个字符串?

c++ - 如何检查一个字符串是否包含多个其他字符串?

java - 从较长的文件路径中获取文件路径的一部分

java - 在Java中画椭圆

java - 如何决定在 Spring Security PersistentTokenRepository.removeUserTokens 中删除哪个持久 token

java - 从 Swing GUI 编译和运行 Java 代码

java - Eclipse hibernate pojo 生成包括外键

java - String.intern() 究竟是如何工作的