我不知道如何在JAVA中将整数转换为24小时格式。

例如:

public class Activity
{
   private Subject subject;
   private int start;
   private int duration;
   private String room;
   private int capacity;
   private int enrolled;


public Activity(Subject subject, int start, int duration, String room, int capacity)
{
    this.subject = subject;
    this.start = start;
    this.duration = duration;
    this.room = room;
    this.capacity = capacity;
}

@Override
public String toString()
{
    return subject.getNumber() + " " + start + " " + duration + "hrs" + " " + enrolled + "/" + capacity;
}
}


在toString()方法中,我想将int可变起始内容转换为HH:00格式。起始变量是0到18之间的整数。
我试图添加这样的方法:

public String formatted(int n)
{
    int H1 = n / 10;
    int H2 = n % 10;
    return H1 + H2 + ":00";
}


然后将变量start传递给此方法。但这是行不通的。我不明白哪里出了问题。

在这方面,我需要一些帮助!

PS:结果应类似于“ 48024 18:00 1hrs 0/200”,我得到了除起始变量之外所有其他格式正确的变量。

最佳答案

您的方法失败,因为您的代码等效于:

return (H1 + H2) + ":00";


因此,它会在附加字符串之前汇总每个数字!

您可以通过以下方式“纠正”(或实际修改)它:

return H1 + (H2 + ":00");


甚至更好,使用String.format

public String formatted(int n) {
    // print "n" with 2 digits and append ":00"
    return String.format("%02d:00", n);
}

10-06 06:19
查看更多