|
题目:
Time 类
其中有两个私有成员变量 hour 和minute 类型都是int
写一个构造函数给这两个成员变量赋初值,假设两个参数的值都是合理的。
例如hour的范围都是在0~23之间,而minute都是在0~59之间。
写一个static方法叫做difference, 这个方法接受两个参数t1和t2,返回t1跟t2之间相差的分钟数。
例如,t1 = 6:35 而t2 = 8:20那么这个方法的返回值是105。120-15 = 105
写一个toString()方法把一个时间对象转变为格式为08:25或者10:02。
我写的代码:(但有问题,望大虾指点一下。)
//Time.java
public class Time{
int hour;
int minute;
Time() {
hour = 0;
minute = 0;
}
Time(int h, int m) {
hour = h;
minute = m;
}
public static int difference(Time t1, Time t2) {
return (t2.hour - t1.hour) * 60 + (t2.minute - t1.minute);
}
public static String toString(Time t1, Time t2) {
if ( difference(t1,t2)/60 < 10 ){
if(difference(t1,t2)%60 < 10)
return "0" + (difference(t1,t2)/60)
+":" + "0"
+(difference(t1,t2) - difference(t1,t2)/60*60);
else if(difference(t1,t2)%60 >= 10)
return "0" + (difference(t1,t2)/60)
+":"
+(difference(t1,t2) - difference(t1,t2)/60*60);
}
else if( difference(t1,t2)/60 >= 10){
if ( difference(t1,t2)/60 < 10 )
if(difference(t1,t2)%60 < 10)
return (difference(t1,t2)/60)
+":" + "0"
+(difference(t1,t2) - difference(t1,t2)/60*60);
else if(difference(t1,t2)%60 >= 10)
return + (difference(t1,t2)/60)
+":"
+(difference(t1,t2) - difference(t1,t2)/60*60);
}
}
public static void main(String arg[]){
//display 01:01
System.out.println(Time.toString(new Time(1,1), new Time(2,2)));
//display 01:10
System.out.println(Time.toString(new Time(2,2), new Time(3,12)));
//display 10:01
System.out.println(Time.toString(new Time(3,3), new Time(13,3)));
//display 10:10
System.out.println(Time.toString(new Time(4,4), new Time(14,14)));
//display 01:45
System.out.println(Time.toString(new Time(5,30), new Time(7,15)));
}
} |
|