gpt4 book ai didi

java - 如何让我的时钟像这样 03 :05:01

转载 作者:行者123 更新时间:2023-12-01 18:05:18 25 4
gpt4 key购买 nike

我有一个java项目。

Create CTime class with the following specifications

  1. Attributes: Hour, minute and second
  2. Hour >=0 and <= 23, minute >=0 and <=59 , second >=0 and <= 59
  3. Methods
    • Constructor that updates the CTime attributes
    • set and get methods for each attribute
    • tick method that add 1 second to the CTime object and returns nothing
    • toString method that creates time string with the following format HH:mm:ss e.g. 22:15:01

我做到了

public class CTime {

int hour;
int min;
int sec;

public CTime(int h, int m, int s) {
hour = h;
min = m;
sec = s;
}

public void setHour(int h) {
hour = h;
}

public int getHour() {
return hour;
}

public void setMin(int m) {
min = m;
}

public int getMin() {
return min;
}

public void setSec(int s) {
sec = s;
}

public int getSec() {
return sec;
}

public void tick() {
sec++;
if (sec >= 59) {
sec = 0;
min++;
if (min >= 59) {
min = 0;
}
hour++;
}
}

public String toString() {
String s = hour + ":" + min + ":" + sec;
return s;
}
}

如何用 2 位数字表示小时、分钟和秒,例如05:02:09?

我的代码是否正确?

最佳答案

如果你坚持用字符串做这种事情,你可以这样做:

public String toString() {
String s = (hour > 9 ? hour : "0" + hour) + ":" + (min > 9 ? min : "0" + min) + ":" + (sec > 9 ? sec : "0" + sec);
return s;
}

关于java - 如何让我的时钟像这样 03 :05:01,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36879224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com