0
我有一個Event類,它使用PriorityQueue和一個Time類,我定義我自己用於Event類。Java PriorityQueue無法正常工作?
static class Event implements Comparable<Event>{
Customer customer;
Time eventTime;
char eventType;
public int compareTo(Event e){
int n = e.eventTime.compareTo(eventTime);
int compare = 0;
if(n < 0){
compare = -1;
}
else if(n == 0){
compare = 0;
}
else if(n > 0){
compare = 1;
}
return compare;
}
}
class Time{
private int hour;
private int minute;
private boolean isMorning;
public Time(){
hour = 0;
minute = 0;
isMorning = true;
}
public Time(int h, int m, boolean morning){
hour = h;
minute = m;
isMorning = morning;
}
public void setTime(int h, int m, boolean morning){
hour = h;
minute = m;
isMorning = morning;
}
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public boolean isAM(){
return isMorning;
}
public String toString(){
String AM = "";
String min = "";
if(minute < 10){
min = ("0" + minute);
}
else{
min = ("" + minute);
}
if(isMorning){
AM = "AM";
}
else{
AM = "PM";
}
return ("" + hour + ":" + min + " " + AM);
}
public Time plus(int n){
Time newTime = new Time();
boolean newMorning = false;
int minutes = minute + n;
int newHour = minutes/60;
int newMinutes = minutes%60;
hour = hour + newHour;
if(hour > 12){
hour = hour - 12;
if(isMorning){
newMorning = false;
}
else{
newMorning = true;
}
}
newTime.setTime(hour, newMinutes, newMorning);
return newTime;
}
public int timeDifference(Time t){
int n = totalMinutes();
int m = t.totalMinutes();
return m - n;
}
public int compareTo(Time t){
int n = totalMinutes();
int m = t.totalMinutes();
int compare = 0;
if(n < m){
compare = -1;
}
else if(n == m){
compare = 0;
}
else if(n > m){
compare = 1;
}
return compare;
}
private int totalMinutes(){
int tempMinute = 0;
if(!isMorning){
if(hour == 12){
}
else{
hour = hour + 12;
tempMinute = (hour*60) + minute;
}
}
else{
if(hour == 12){
tempMinute = minute;
}
else{
tempMinute = (hour*60) + minute;
}
}
return tempMinute;
}
}
這不是我所有的代碼,因爲我有其他人只保存稍後將插入到事件隊列中的值。當我檢查Event隊列之外的時間時,它與它應該的時間相匹配,比如說我在上午11:22有一個Time對象,但是當我將它插入事件隊列時,我的時間變爲23:22 AM。出於某種原因,它在事件隊列中增加了12個小時,我不明白爲什麼。
想通了()方法用的時間,因爲搞亂使用時的compareTo()或爲TimeDifference()隱式地它被稱爲totalMinutes。感謝您的幫助!
在我看來就像你有你的compareTo倒退。雖然沒有讀過你所有的代碼。 – user2357112
'Time.plus'方法似乎與實例自己的「小時」相混淆,而不是新時間的「小時」。 – user2357112
'Time.totalMinutes'也似乎在搞亂'hour'實例字段時,它真的不應該。 – user2357112