在评论版本4下,我试图创建一个名为equals的方法来测试小时,分钟和秒。形式参数在return语句中再次使用。我知道我应该在______。小时格式中使用它,小时是用于测试和产生真或假的实例变量,但我不知道在该期间之前应该作为形式参数应该去做什么。任何建议/解释都将受到重视。
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);
}
public void setTime ( byte hours, byte minutes, byte seconds )
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
// hours
if (DEFAULT_HOUR >= 0 && DEFAULT_HOUR <= 29)
{
}
else
{
hours = DEFAULT_HOUR;
}
// minutes
if (DEFAULT_MIN >= 0 && DEFAULT_MIN <= 59)
{
}
else
{
minutes = DEFAULT_MIN;
}
// seconds
if (DEFAULT_SEC >= 0 && DEFAULT_SEC <= 59)
{
}
else
{
seconds = DEFAULT_SEC;
}
}
//--------------------------
// Version 3 mutator methods
//--------------------------
public void incrementSeconds()
{
seconds += 1;
if (seconds >= 59)
{
seconds = DEFAULT_SEC;
incrementMinutes();
}
}
public void incrementMinutes()
{
minutes += 1;
if (minutes >= 59)
{
minutes = DEFAULT_MIN;
incrementHours();
}
}
public void incrementHours()
{
hours += 1;
if (hours >= 23)
{
hours = DEFAULT_HOUR;
}
}
//----------
// Version 4
//----------
public boolean equals(Clock your_clock)
{
return boolean your_clock.hours;
}
//----------
// Version 2
//----------
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;
}
} // End of class definition
答案 0 :(得分:1)
如果你试图找到参数Clock和来电时钟之间的相等,我会做以下
public boolean equals(Clock another_clock) {
// Check if 'this' is equal to 'another_clock'
// 1. If you're checking if the pointer is the same
return another_clock.equals(this);
// 2. If you're checking if time is the same (You probably need to create getter/setter methods or change privacy for these fields)
return another_clock.hours == this.hours &&
another_clock.minutes == this.minutes &&
another_clock.seconds == this.seconds;
}
或者那些东西。