Java将任意整数转换为4位数字

发布于 2024-12-09 07:15:24 字数 221 浏览 4 评论 0原文

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

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

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

This seems like an easy question. One of my assignments basically sends a time in military format (like 1200, 2200, etc) to my class.

How can I force the integer to be converted to 4 digits when it's received by my class? For example if the time being sent is 300, it should be converted to 0300.

EDIT: it turns out i didnt need this for my problem as i just had to compare the values. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小苏打饼 2024-12-16 07:15:24

就这么简单:

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;
}

As simple as that:

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

For comparing hours before minutes:

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);
}

Note:

Integer.compare(i1, i2) has been added in Java 1.7, for previous version you can either use Integer.valueOf(i1).compareTo(i2) or

int comparationResult;
if (i1 > i2) {
    comparationResult = 1;
} else if (i1 == i2) {
    comparationResult = 0;
} else {
    comparationResult = -1;
}
晨曦÷微暖 2024-12-16 07:15:24

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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文