使用parseInt()和子字符串的java时差
我正在创建一个程序来找出两个输入之间的时间差。开始和结束时间以12小时格式输入,如上午9:30和11:15
我已经读取了字符串,使用substring函数提取字符串(直到“:”),然后转换为整数。提取效果非常好
我的问题在于计算。e、 g.-下午1:03和12:56之间的时差为1433分钟。但我的程序显示,相差713分钟
我有代码的计算部分。如有任何建议,将不胜感激
// If-else statements to calculate the total time difference
if((lower1.indexOf('a') == -1) && (lower2.indexOf('a') == -1) && (intMin1 <= 60) && (intMin2 <= 60)){
timeDifference = Math.abs((((intHrs1+12)*60)+intMin1) - (((intHrs2+12)*60)+intMin2));
System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') != -1) && (lower2.indexOf('a') == -1) && (intMin1 <= 60) && (intMin2 <= 60)) {
timeDifference = Math.abs((((intHrs2+12)*60)+intMin2) - ((intHrs1*60)+intMin1));
System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') != -1) && (lower2.indexOf('a') != -1) && (intMin1 <= 60) && (intMin2 <= 60)){
timeDifference = Math.abs(((intHrs2*60)+intMin1) - ((intHrs1*60)+intMin2));
System.out.println("The time difference is " + timeDifference + " minutes");
} else if((lower1.indexOf('a') == -1) && (lower2.indexOf('a') != -1) && (intMin1 <= 60) && (intMin2 <= 60)){
timeDifference = Math.abs((((24-(intHrs1+12))*60)+intMin1) - ((intHrs2*60)+intMin2));
System.out.println("The time difference is " + timeDifference + " minutes");
} else if(intMin1 >= 60){
System.out.println("Error: The First time is invalid");
} else {
System.out.println("Error: The second time is invalid");
}
# 1 楼答案
不要为此使用parseInt和substring:
# 2 楼答案
要使代码可读和可测试,请创建助手方法
输出