这是给出的任务:
对于此作业,您将从作业1更新时间类。要开始,您可以复制作业1 Time.java,或下载解决方案Time.java。 首先,您需要更新Time以便它实现Comparable接口。这将需要在类声明和compareTo方法中添加一个implements语句。然后,您需要在类中添加差异方法。这两种方法'要求如下:
compareTo(Object other)
//Returns -1 if current time is less than other.
//Returns 0 if current time is equal to other.
//Returns 1 if current time is greater than other.
String difference(Time t)
//Returns a String holding the difference between the current time and
//the Time t passed in via parameter. All values should be positive,
//and in the format:
//Time difference: 08:09
//Time difference: 10:35
要测试代码,请下载并运行runner类:student_runner_time.java。我们将使用不同但相似的测试类来对程序进行评分。您需要更改运行器以使用其他值进行测试,以确保您的程序符合所有要求。
Sample Run of student_runner_time.java:
1712
0945
Greater than:
1
Less than:
-1
Times equal:
0
Hours equal:
1
-1
Difference
Time difference: 00:11
Time difference: 00:11
Time difference: 00:00
注意:您必须使用班级名称"时间"这项任务。请记住:您必须提交您的答案。除非已提交,否则您的作业不会被视为完成。
这是我提交的内容:
public class Time implements Comparable<Time> {
private int hour;
private int minute;
/*
Sets the default time to 12:00.
*/
public Time() {
this(12, 0);
}
/*
Sets hour to h and minute to m.
*/
public Time(int h, int m) {
hour = 0;
minute = 0;
if (h >= 1 && h <= 23)
hour = h;
if (m >= 1 && m <= 59)
minute = m;
}
/*
Returns the time as a String of length 4 in the format: 0819.
*/
public String toString() {
String h = "";
String m = "";
if (hour < 10)
h += "0";
if (minute < 10)
m += "0";
h += hour;
m += minute;
return "" + h + "" + m;
}
public String difference(Time that) {
int thisMin = this.hour * 60 + this.minute;
int thatMin = that.hour * 60 + that.minute;
int diffMin = Math.abs(thisMin - thatMin);
int diffH = diffMin / 60;
int diffM = diffMin % 60;
String h = "";
String m = "";
if (diffH < 10) {
h += "0";
}
if (diffM < 10) {
m += "0";
}
h += diffH;
m += diffM;
return h + ":" + m;
}
@Override
public int compareTo(Time that) {
int thisMin = this.hour * 60 + this.minute;
int thatMin = that.hour * 60 + that.minute;
if (thisMin < thatMin) {
return -1;
} else if (thisMin > thatMin) {
return 1;
} else {
return 0;
}
}
}
这些是我收到的错误:
您的代码已根据一组测试数据进行评估
你有7个测试中的3个正确通过。
你的分数是42%。
失败的测试是:
Test2: difference()
Incorrect: First Time Less
Incorrect: First Time Greater
Incorrect: Large Difference
Incorrect: Small Difference