在我的计算机科学课上遇到麻烦: 您需要更新Time(见下文),以便它实现Comparable接口。这将需要在类声明和compareTo方法中添加一个implements语句。然后,您需要在类中添加差异方法。这两种方法的要求如下: compareTo(Object other):如果当前时间小于other,则返回-1。如果当前时间等于other,则返回0。如果当前时间大于其他时间,则返回1.
字符串差异(时间t):返回一个String,它保存当前时间与via参数中传递的Time t之间的差值。所有值都应为正数,格式为: // 08:09 // 10:35 要测试代码,请运行runner类(参见下文)。您需要更改运行器以使用其他值进行测试,以确保您的程序符合所有要求。
student_runner_time.java的示例运行:
1712
0945
大于: 1
小于: -1
时代相等: 0
小时数: 1
-1
差分
0点11分
0点11分
0时
时间:
public class Time implements Comparable
{
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 int compareTo(Object other){
if(t1<t2){
return -1;
}
else return 0;
}
String difference(Time t){
return "";
}
}
student time runner:
import java.io.IOException;
import java.util.Scanner;
class student_time_runner
{
public static void main(String str[]) throws IOException
{
Scanner scan = new Scanner(System.in);
// time 1
Time t1 = new Time(17, 12);
System.out.println(t1);
Time t2 = new Time(9, 45);
System.out.println(t2);
System.out.println("Greater Than:");
System.out.println(t1.compareTo(t2));
System.out.println("Less Than:");
System.out.println(t2.compareTo(t1));
System.out.println("Times equal:");
Time t3 = new Time(9, 45);
System.out.println(t3.compareTo(t2));
System.out.println("Hours equal:");
Time t4 = new Time(8, 45);
Time t5 = new Time(8, 34);
System.out.println(t4.compareTo(t5));
System.out.println(t5.compareTo(t4));
System.out.println("Difference");
System.out.println(t4.difference(t5));
System.out.println(t5.difference(t4));
System.out.println(t4.difference(t4));
}// main
}// class
答案 0 :(得分:1)
您的compareTo方法并不是真正的比较。它应该像这样
public int compareTo(Object other){
int timeDiff = this.getHour()*60 + this.getMinute() - other.getHour()*60 - other.getMinute();
if(timeDiff>0){
return -1;
}
if(timeDiff<0){
return 1;
}
else return 0;
}
此外,您必须确保添加两个getter。