在java中实现已有一个日期类Date,包括三个protected成员数据 int year; int month; int day; 另有一个时间类Time,包括三个protected成员数据 int hour; int minute; int second; 现需根据输入的日程的日期时间,安排前后顺序,为此以Date类和Time类为基类,建立一个日程类Schedule,包括以下新增成员: int ID;//日程的ID bool operator < (const Schedule & s2);//判断当前日程时间是否早于s2 生成以上类,并编写主函数,根据输入的各项日程信息,建立日程对象,找出需要最早安排的日程,并输出该日程对象的信息。 输入格式: 测试输入包含若干日程,每个日程占一行(日程编号ID 日程日期(****//)日程时间(::**))。当读入0时输入结束,相应的结果不要输出。 输入样例: 1 2014/06/27 08:00:01 2 2014/06/28 08:00:01 0 输出样例: The urgent schedule is No.1: 2014/6/27 8:0:1
时间: 2023-06-16 15:04:49 浏览: 274
以下是Java的实现代码,其中重载了compareTo方法来实现Schedule对象的比较:
```
import java.util.*;
class Date {
protected int year;
protected int month;
protected int day;
public Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
public String toString() {
return String.format("%d/%d/%d", year, month, day);
}
}
class Time {
protected int hour;
protected int minute;
protected int second;
public Time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
public String toString() {
return String.format("%d:%d:%d", hour, minute, second);
}
}
class Schedule extends Date implements Comparable<Schedule> {
protected int ID;
protected Time time;
public Schedule(int id, int y, int m, int d, int h, int min, int s) {
super(y, m, d);
ID = id;
time = new Time(h, min, s);
}
public boolean earlierThan(Schedule s2) {
if (year < s2.year) {
return true;
} else if (year == s2.year && month < s2.month) {
return true;
} else if (year == s2.year && month == s2.month && day < s2.day) {
return true;
} else if (year == s2.year && month == s2.month && day == s2.day && hour < s2.time.hour) {
return true;
} else if (year == s2.year && month == s2.month && day == s2.day && hour == s2.time.hour && minute < s2.time.minute) {
return true;
} else if (year == s2.year && month == s2.month && day == s2.day && hour == s2.time.hour && minute == s2.time.minute && second < s2.time.second) {
return true;
}
return false;
}
public int compareTo(Schedule s2) {
if (earlierThan(s2)) {
return -1;
} else if (s2.earlierThan(this)) {
return 1;
}
return 0;
}
public String toString() {
return String.format("No.%d: %s %s", ID, super.toString(), time.toString());
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Schedule> schedules = new ArrayList<>();
while (true) {
int id = sc.nextInt();
if (id == 0) {
break;
}
String date = sc.next();
String time = sc.next();
String[] dateParts = date.split("/");
String[] timeParts = time.split(":");
int y = Integer.parseInt(dateParts[0]);
int m = Integer.parseInt(dateParts[1]);
int d = Integer.parseInt(dateParts[2]);
int h = Integer.parseInt(timeParts[0]);
int min = Integer.parseInt(timeParts[1]);
int s = Integer.parseInt(timeParts[2]);
Schedule schedule = new Schedule(id, y, m, d, h, min, s);
schedules.add(schedule);
}
Collections.sort(schedules);
System.out.println("The urgent schedule is " + schedules.get(0).toString());
}
}
```
阅读全文