2009-12-24 84 views
1

我嘗試編程基數排序,但我有NullPointerException異常,當我運行這段代碼排序問題?

public class ThreeRadixSort { 

    public Queue getSortedData(Queue queue){ 
     Queue array[] = new Queue[10]; 


     for(int i=1;i<=3;i++){ 

     while(queue.front != null){ 
      Student student = queue.dequeue(); 


      if(i == 1) 
       array[(int)(student.id%10)].enqueue(student); 
      else if(i == 2) 
       array[(int)((student.id%100)/10)].enqueue(student); 
      else  
       array[(int)(student.id/100)].enqueue(student); 

     } 

     for(int j=0;j<=9;j++){ 

     while(array[j] != null && array[j].front != null) 
      queue.enqueue(array[j].dequeue()); 
     } 
     } 
     return queue; 
    } 
} 

例外節目在這裏當工具達到

array[(int)(student.id%10)].enqueue(student); 

回答

2

的問題是,當你初始化數組Queue,每個點都被初始化爲空。所以現在,您正試圖撥打enqueue方法null。您需要遍歷數組的每個位置併爲其指定一個new Queue()或者您將其初始化。

因此,例如:

for (int i = 0; i < array.length; i++) { 
    array[i] = new Queue(); 
} 
+0

thanx,問題解決 – wasim 2009-12-24 14:27:36

+0

不客氣 - 你會介意改裝/接受這個答案,如果它爲你工作? – danben 2009-12-24 14:28:40

+0

oK ..i做了這個 – wasim 2009-12-24 14:38:57

1

這一行:

Queue array[] = new Queue[10] 

僅聲明隊列陣列。它不會自己分配隊列。 你應該像這樣初始化它們:

for(int i; i<10; i++) 
{ 
     array[i] = new Queue(); 
} 

p.s.順便一提。不要依賴像'10'這樣的魔術數字,最好讓它成爲一個常量並在程序的頂部聲明。像這樣:

const int numElements = 10; 
+0

我會傾向於同意你關於魔術數字的陳述,除非常數永遠不會改變 - 然後我覺得它只是降低了可讀性(因爲它向讀者表明它可能會改變)。在這種情況下,他的隊列數量改變的唯一方法是他是否在10以外的基礎上實現算法,這似乎不大可能。 – danben 2009-12-24 14:13:31

+0

thanx,問題解決了 – wasim 2009-12-24 14:30:39

+0

我會傾向於你的想法,但本 – wasim 2009-12-24 14:35:01