我正在生成一个代码,该代码采用用户的 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/