日期:2014-05-20  浏览次数:20655 次

2013北邮java教程第4次实验Time类

1.完成Time类,要求该类能够实现以下功能:

a.      该类以小时和分钟显示一天中的时间;提供两种计时功能,一种以24小时计时,一种以12小时计时;默认以24小时计时;

b.      可以以当前时间构造对象;

c.      可以设置一个特定的时间来构造对象;

d.      能够访问时间的小时数;

e.      能够访问时间的分钟数;

f.       提供方法能够将时间增加1小时;

g.      提供方法能够将时间增加特定的小时;

h.      提供方法能够将时间增加1分钟;

i.       提供方法能够将时间增加n分钟;

j.       提供toString( )方法用来打印时间,以24小时计时,输出“23:30”;以12小时计时,输出“00:15AM”,“12:00PM”,“11:59PM”。

测试自己写的类。

今天早晨起的挺早,脑袋昏昏沉沉的所以导致代码质量不高,望海涵。

放代码:

import java.util.*;
import static java.lang.System.*;
public class Time {


/**
* @param args
* @author Chenxingman
* @serialData 2013-4-10
*/
public Time(int ahour,int amin,int asec,String atype)
{
hour=ahour;
min=amin;
sec=asec;
type=atype;
}
public Time(int ahour,int amin,int asec)
{
hour=ahour;
min=amin;
sec=asec;
type="A";
}
public Time()
{
 Calendar ca = Calendar.getInstance();
     hour=ca.get(Calendar.HOUR);//小时
     min=ca.get(Calendar.MINUTE);//分
     sec=ca.get(Calendar.SECOND);//秒
     type="A";
}
public static void main(String[] args) {
Time test2=new Time();
Time test3=new Time(23,50,50);
Time test=new Time(11,50,50,"PM");
out.print("Local Time: ");
test.ToString();
out.println("Set hour ahead as 2:");
test.setHour(2);
test.ToString();
out.println("Set min ahead as 30:");
test.setMin(30);
test.ToString();
out.println("gethour:"+test.getHour()+"getmin:"+test.getMin()+"getsec:"+test.getSec());
out.println("set hour and min ahead:");
test.setAheadhour();
test.setAheadmin();
test.ToString();

}
public int getHour()
{
if(type.length()==2)
{
hour+=min/60;
if(hour/12>0)
{
if(type.equals("AM"))
type="PM";
else if(type.equals("PM"))
type="AM";
}
hour=hour%12;
min=min%60;
}
else
{hour+=min/60;
hour=hour%24;
min=min%60;}
return hour;
}
public int getMin()
{
if(type.length()==2)
{
hour+=min/60;
if(hour/12>0)
{
if(type.equals("AM"))
type="PM";
else
type="AM";
}
hour=hour%12;
min=min%60;
}
else
{hour+=min/60;
hour=hour%24;
min=min%60;}
return min;
}
public int getSec()
{
return sec;
}
public void setHour(int ahour)
{
hour+=ahour;
}
public void setAheadhour()
{
hour++;
}
public void setAheadmin()
{
min++;
}
public void setMin(int amin)
{
min+=amin;
}
public void ToString()
{
if(type.length()==2)
{
hour+=min/60;
if(hour/12>0)
{
if(type.equals("AM"))
type="PM";
else
type="AM";
}
hour=hour%12;
min=min%60;
}
else
{
hour+=min/60;
   hour=hour%24;
   min=min%60;
}

if(hour<10)
out.print("0"+hour+":");
else out.print(hour+":");
if(min<10)
out.print("0"+min+":");
else out.print(min+":");
if(sec<10)
out.print("0"+sec);
else out.print(sec);
if(type.length()==1)
   out.println();
else
out.println(type);
}
    private int hour;
    private int min;
    private int sec;
    private String type;
}