【发布时间】:2020-10-03 05:33:21
【问题描述】:
我正在制作一个程序,旨在通过军事时间获取经过的时间,这就是我到目前为止得到的:
public class TimeInterval {
private int firstTime;
private int secondTime;
public TimeInterval(int _first,int _second) {
if (_first < 0 || _second < 0) {
System.out.println("ERROR INVALID INPUT");
System.exit(0);
}
else if (_first > 2400 || _second > 2400) {
System.out.println("ERROR INVALID INPUT");
System.exit(0);
}
else
firstTime = Math.max(_first, _second);
secondTime = Math.min(_first,_second);
}
}
public int getHours() {
return (Integer.parseInt(Integer.toString(firstTime).substring(0, 2)))-(Integer.parseInt(Integer.toString(secondTime).substring(0, 2)));
}
}
除了处理从 0000 到 0700 的 _first 或 _second 输入外,该程序大部分时间都可以工作。想法是它们被读取为军事时间,但 java 将它们读取为基数 8 整数,因此当 _first = 0700 和 _second = 1400 我得到 448 或其他东西。无论如何我可以确保当 _first 和 _second 输入到 Math.min 时,它们被读取为基数 10 而不是基数 8。
【问题讨论】:
-
为什么将时间存储为
int?您应该将时间存储为LocalTime。 -
问题不在
Math.min。问题甚至不在此代码中。问题很可能出在您测试此代码的方式上。 Java 整数文字0700实际上表示 448。前导零使其成为八进制文字。请注意,这仅适用于文字,而不适用于使用(例如)Integer.parseInt转换为整数的字符串。 -
但要注意的另一件事是“0700”在概念上不是整数。实际上是“07”小时+“00”分钟;即两个整数。所以概念上正确的表示它的方法是Java字符串;即
"0700". -
@StephenC 或者更正确的是,两个整数。然后你也可以从 java.time 到
LocalTime。 -
这是真的....
标签: java math octal timeofday military