说明:时间类的练习
1)定义时间类,封装小时、分钟和秒
2)重载构造函数,支持初始化
3)重写toString方法,支持格式化输出
4)定义add方法,实现时间累加,在累加后,小时、分钟和秒自动求模,并且能够向上进值
5)定义setTime方法,实现时间赋值,能够自动求模,并且能向上进值
6)能够在任意设置时间操作后进行验证,能够自动求模,并且能向上进值
注意:如对于应用程序:
public class exec
{
public static void main(String[] args)
{
Time t=new Time();
t.setTime(10,60,60);
t.add(10,60,60);
System.out.println(t);
}
}
输出为:10:02:00PM
代码为:
public class Time
{
private int hour;
private int minute;
private int second;
public Time()
{
hour=0;
minute=0;
second=0;
}
public Time(int h,int m,int s)
{
setHour(h);
setMinute(m);
setSecond(s);
}
public void setHour(int h)
{
hour=h;
validate();
}
public int getHour()
{
return hour;
}
public void setMinute(int m)
{
minute=m;
validate();
}
public int getMinute()
{
return minute;
}
public void setSecond(int s)
{
second=s;
validate();
}
public int getSecond()
{
return second;
}
public String toString()
{
java.text.DecimalFormat df=new java.text.DecimalFormat("00");
return df.format(hour%12)+":"+df.format(minute)+":"+df.format(second)+(hour<12?"AM":"PM");
}
public void add(int h,int m,int s)
{
second+=s;
minute+=m;
hour+=h;
validate();
}
public void setTime(int h,int m,int s)
{
second=s;
minute=m;
hour=h;
validate();
}
private void validate()
{
if(second>=60)
{
minute+=second/60;
second=second%60;
}
if(minute>=60)
{
hour+=minute/60;
minute=minute%60;
}
if(hour>=24)
{
hour=hour%24;
}
}
}
[此贴子已经被作者于2010-12-12 08:13:59编辑过]