對對象數組進行排序我可能會比這更難......但我的任務是創建一個實現Comparable的放映時間類。有了它,它就構建了幾種不同劇院的列表,以及電影所顯示的內容和時間等。然後,我必須使用compareTo()方法首先對它顯示的電影和電影進行排序標題。我有以下代碼...當我嘗試輸出排序結果時出現混淆。我將它輸出到比較字符串的位置 - 或+號。使用compareTo()
public class ShowTimeTest {
public static void main(String[] args) {
ShowTime[] movieTimes= new ShowTime[20];
// TODO Auto-generated method stub
//******************************************************
//Instantiates 20 showtime objects
//******************************************************
ShowTime cinemark1 = new ShowTime("Cinemark", "Lorde", "Friday @ 3:30", "Saturday @ 7:00", "Sunday @ 6:00","R", 1, 2);
ShowTime cinemark2 = new ShowTime("Amstar Cinemas", "Star Wars", "Thursday @ 12:00AM", "Monday @ 4:00PM", "Sunday @ 3:45PM","R", 1, 2);
ShowTime cinemark3 = new ShowTime("Fayette Movies", "Pokemon", "Friday @ 3:30", "Saturday @ 7:00", "Sunday @ 6:00","R", 1, 2);
ShowTime cinemark4 = new ShowTime("Dollar Theatre", "Reincarnated", "Friday @ 3:30", "Saturday @ 7:00", "Sunday @ 6:00","R", 1, 2);
ShowTime cinemark5 = new ShowTime("Rad Chads Cinemas", "Lorde", "Friday @ 3:30", "Saturday @ 7:00", "Sunday @ 6:00","R", 1, 2);
movieTimes[0] = cinemark1;
movieTimes[1] = cinemark2;
movieTimes[2] = cinemark3;
movieTimes[3] = cinemark4;
movieTimes[4] = cinemark5;
for(int i = 1; i < 5; i ++){
System.out.println(movieTimes[i].compareTo(movieTimes[i-1]));
}
}
}
續...
public class ShowTime implements Comparable<ShowTime>{
public String name, title, rating, showTime1, showTime2, showTime3;
public double ticket, adultTicket;
public String[] times = new String[3];
public ShowTime(String theatreName, String movieTitle, String showTime1, String showTime2, String showTime3 , String movieRating, double childTicket, double aTicket)
{
// TODO Auto-generated constructor stub
name = theatreName;
title = movieTitle;
times[0] = showTime1;
times[1] = showTime2;
times[2] = showTime3;
rating = movieRating;
ticket = childTicket;
adultTicket = aTicket;
}
public String toString(){
String out = "Theatre: ";
out += name+ " " + "Movie: " + title + " " + "Rating " + rating + " " + "ShowTimes " + times[0] + " " + times[1] + " " + times[2]
+ " " + "Adult Cost: " + adultTicket + " " + "Child Ticket: " +ticket;
return out;
}
public int compareTo(ShowTime other) {
// TODO Auto-generated method stub
//sorts the showtimes by theater(NAME) and movie(TITLE)
int result;
if(name.equals(((ShowTime)other).name)){
result = title.compareTo(((ShowTime)other).title);
}
else{
result = name.compareTo(((ShowTime)other).name);
}
return result;
}
}
就快完成了 - 現在只是排序! – mbroshi
謝謝!很高興聽到我確實在做正確的事情。我在分揀事物時感到很失落,就像我花了我所有的大腦力量做上述 – cdc09
,如果你調用Arrays.sort(movieTimes),你將得到一個'NullPointerException';''因爲你只是初始化了5個元素,但你已經分配了20個。 – jfly