2012-10-25 25 views
0

我使用Arrays.sort方法來排序我自己的Comparable對象的數組。在使用sort之前,數組已滿,但在對數組進行排序並將其打印到System之後,沒有任何內容正在打印出來。編輯。陣列根本沒有打印任何東西。不是空行,只是沒有。使用Arrays.sort,空數組返回

這裏是我的方法,它使用sort代碼:

public LinkedQueue<Print> arraySort(LinkedQueue<Print> queue1) 
{ 
    Print[] thing = new Print[queue1.size()]; 
    LinkedQueue<Print> newQueue = new LinkedQueue<Print>(); 

    for(int i = 0; i <queue1.size(); i++) 
    { 
     Print ob = queue1.dequeue(); 
     thing[i] = ob; 
     System.out.println(thing[i]); //printing works here 
    } 

    Arrays.sort(thing); 

    for(int j = 0;j<thing.length-1;j++) 
    { 
     System.out.println(thing[j]); //printing does not work here 
     newQueue.enqueue(thing[j]); 
    } 

    return newQueue; 
} 

,這裏是名爲PrintComparable對象的類。

public class Print implements Comparable<Print> 
{ 
    private String name; 
    private int numPages,arrivalTime,startTime,endTime; 

    public Print(String n, int p, int time, int sTime, int eTime) 
    { 
     name = n; 
     numPages = p; 
     arrivalTime = time; 
     startTime = sTime; 
     endTime = eTime; 
    } 

    public int getPages() 
    { 
     return numPages; 
    } 

    public int compareTo(Print other) 
    { 
     if(this.getPages()<other.getPages()) 
      return -1; 

     else if(this.getPages()>other.getPages()) 
      return 1; 

     else 
      return 0; 
    } 

    public String toString() 
    { 
     return name+"("+numPages+" pages) - printed "+startTime+"-"+endTime+" minutes"; 
    } 
} 
+6

爲什麼你不打印出最後一個元素? 'for(int j = 0; j

+2

另外,「打印在這裏不起作用」是什麼意思?是*什麼*被打印?錯誤的值? –

+1

由於您在'Print'類中覆蓋了'toString',因此您可以使用'Arrays.toString(thing)'進行打印。並告訴我們輸出的是什麼。 –

回答

1

您最後的for循環不打印數組中的最後一個元素。如果數組只有一個元素,它將不會打印任何東西。更改爲:

for (int j = 0; j < thing.length; j++) //clean code uses spaces liberally :) 
{ 
    System.out.println(thing[j]); 
    newQueue.enqueue(thing[j]); 
} 

或者(如果使用的JDK/JRE版本支持):

for (Print p : thing) 
{ 
    System.out.println(p); 
    newQueue.enqueue(p); 
} 
+1

*「乾淨的代碼使用空間寬鬆」*真是一個個人喜好的問題。我認爲'int j = 0'是醜陋的。 – NullUserException

+0

好吧。我不爭論:) – ADTC

+0

謝謝!這是問題所在。 – bitva

-1

我希望這些問題是這部分代碼

for(int i = 0; i <queue1.size(); i++) 
{ 
    Print ob = queue1.dequeue(); 
    thing[i] = ob; 
    System.out.println(thing[i]); //printing works here 
} 

替換以上

for(int i = 0; !queue1.isEmpty() ; i++) 
{ 
    Print ob = queue1.dequeue(); 
    thing[i] = ob; 
    System.out.println(thing[i]); //printing works here 
} 
+0

誰說'LinkedQueue'有一個'.isEmpty()'方法? – NullUserException

+0

反正LinkedQueue究竟是什麼?據我所知,在Java中沒有標準的LinkedQueue實現,並且在互聯網中有很多不同的自定義實現,特別是在大學網站上。 – ADTC

+0

@ADTC我假定使用LinkedList實現的非標準隊列。 – NullUserException