说明是....从一个空字符串开始测试小时,并在字符串后面加零,然后在小时内有一位数字的小时或者附加两位数小时。使用最终变量MIN_2DIGITS进行测试,只使用+ =运算符追加正在创建的字符串....代码必须进入注释代码,这里接近底部, 特别是我需要以##:##:## format
中输入的小时,分钟,秒的方式格式化时间到目前为止我已经尝试了这个但是当用户输入小时,分钟和秒时它只输出00:00:00
public class Clock
{
private static final byte DEFAULT_HOUR = 0,
DEFAULT_MIN = 0,
DEFAULT_SEC = 0,
MAX_HOURS = 24,
MAX_MINUTES = 60,
MAX_SECONDS = 60;
// ------------------
// Instance variables
// ------------------
private byte seconds,
minutes,
hours;
public Clock (byte hours , byte minutes , byte seconds )
{
setTime(hours, minutes, seconds);
}
public Clock ( )
{
setTime(DEFAULT_HOUR, DEFAULT_MIN, DEFAULT_SEC);
}
//----------
// Version 2
//----------
public String toString()
{
final byte MIN_2DIGITS = 10;
String str = "";
// CODE GOES HERE, what i have below didn't work
public String toString()
{
final byte MIN_2DIGITS = 10;
String str = "";
// my input
if (hours < MIN_2DIGITS)
{
str += "0" + hours + ":" ;
}
else
str += hours;
if (minutes < MIN_2DIGITS)
{
str += "0" + minutes + ":" ;
}
else
str += minutes;
if (seconds < MIN_2DIGITS)
{
str += "0" + seconds;
}
else
str += seconds;
//end of my input
return str;
}
return str;
}
} // End of class definition
答案 0 :(得分:0)
你快到了。
需要添加以下方法。
public void setTime(byte hours, byte minutes, byte seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
更改以下方法。
public String toString()
{
final byte MIN_2DIGITS = 10;
String str = "";
// my input
if (hours < MIN_2DIGITS) {
str += "0" + hours + ":";
} else
str += hours + ":";
if (minutes < MIN_2DIGITS) {
str += "0" + minutes + ":";
} else
str += minutes + ":";
if (seconds < MIN_2DIGITS) {
str += "0" + seconds;
} else
str += seconds;
// end of my input
return str;
}
测试代码的方法。
public static void main(String[] args) {
Clock clock = new Clock((byte) 9, (byte) 10, (byte) 35);
System.out.println(clock);
}