22

这似乎是一个简单的问题。我的一项作业基本上是向我的班级发送军事格式的时间(例如12002200等)。

当我的班级收到整数时,如何强制将其转换为 4 位数字?例如,如果发送的时间是300,它应该被转换为0300

编辑:事实证明我不需要这个来解决我的问题,因为我只需要比较这些值。谢谢

4

2 回答 2

43

就如此容易:

String.format("%04d", 300)

比较分钟之前的小时:

int time1 =  350;
int time2 = 1210;
//
int hour1 = time1 / 100;
int hour2 = time2 / 100;
int comparationResult = Integer.compare(hour1, hour2);
if (comparationResult == 0) {
    int min1 = time1 % 100;
    int min2 = time2 % 100;
    comparationResult = Integer.compare(min1, min2);
}

笔记:

Integer.compare(i1, i2)已在 Java 1.7 中添加,对于以前的版本,您可以使用Integer.valueOf(i1).compareTo(i2)

int comparationResult;
if (i1 > i2) {
    comparationResult = 1;
} else if (i1 == i2) {
    comparationResult = 0;
} else {
    comparationResult = -1;
}
于 2011-10-11T04:33:33.073 回答
1

String a = String.format("%04d", 31200).substring(0, 4);
/**Output: 3120 */ 
System.out.println(a);


String b = String.format("%04d", 8).substring(0, 4);
/**Output: 0008 */
System.out.println(b);
于 2019-08-09T06:35:23.433 回答