Java将任何整数转换为4位数

Cod*_*ody 19 java format integer zero-pad

这似乎是一个简单的问题.我的一个任务,基本上将在军事格式的时间(如1200,2200等),以我的课.

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

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

Ale*_*rov 38

就如此容易:

String.format("%04d", 300)
Run Code Online (Sandbox Code Playgroud)

比较分钟前的小时数:

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);
}
Run Code Online (Sandbox Code Playgroud)

注意:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 那你为什么要打扰它的位数呢?只需将其存储为常规整数,并在需要进行零填充时通过`String.format`进行打印. (2认同)