说明如下。。。。从一个空字符串开始测试小时数,当小时数中有一位数字时,在字符串后面加一个零,然后加小时数,否则加两位数字的小时数。对测试使用最终变量MIN_2DIGITS,并且只使用+=运算符来附加正在创建的字符串。。。。代码必须进入注释代码在这里接近底部,具体来说,我需要以一种方式格式化时间,即在##:##:##格式中输入的小时、分钟、秒
到目前为止,我已经尝试过了,但当用户输入小时、分钟和秒时,它只输出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
你差不多到了。
需要添加以下方法。
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);
}