2013-03-24 83 views
0

我一直在努力工作,現在已經很久了,我正在運行一個nullpointerexception。我明白,當一個對象指向什麼都不是。在Java中進行冒泡排序時出現這個錯誤。我無法弄清楚是什麼導致這個異常,因此無法解決它。此代碼的目的是按特定順序對學生ID號數組進行排序,我已選擇降序排列。用Java氣泡排序的Nullpointerexception

public static void idNumber() 
    { 
     String[] iD = new String[150]; //array for ID Numbers 
     //System.out.println("Original order"); 
     for(int i = 0; i < nNumStudents; i++) //add ID numbers to array iD 
     { 
      iD[i] = srStudents[i].getStudentKey(); 

      //System.out.println(srStudents[i].getStudentKey()); 
     } 
     //bubble sort 
     int k =0; 
     int j =0; 
     boolean exchange = true; 
     String temp; 
     temp = new String(); 
     while ((k < iD.length - 1) && exchange) 
     { 
      exchange = false; 
      k++; 
      for(j = 0; j < iD.length - k; j++) 
      { 
       if(iD[j].compareTo(iD[j + 1]) > 0) 
       { 
        temp = iD[j]; 
        iD[j] = iD[j + 1]; 
        iD[j + 1] = temp;  
        exchange = true; 

       } 
      } 
     } 
     System.out.println(iD); 
    } 

Exception in thread "main" java.lang.NullPointerException 
at java.lang.String.compareTo(String.java:1139) 
at StudentRegistrar.idNumber(StudentRegistrar.java:152) 
at Sort.main(Sort.java:21) 
+1

你得到空指針是什麼行?共享日誌,並且在特定的行上聲明 – 2013-03-24 22:24:36

+0

我在提供錯誤的行中添加了錯誤消息...我不知道當您詢問日誌時您要求什麼?如果可以,請通知我。謝謝 – user2205621 2013-03-24 22:31:15

+0

打印'j'的值。可能它超過了150。 – Maroun 2013-03-24 22:33:52

回答

0

從你的代碼的一瞥,我的猜測是,它可能是你的數組大小超過學生人數。如果是這樣的話,你試圖比較數組中的空插槽,這會給出空指針異常。爲了解決這個問題,增加到nNumStudents而不是數組的全長。

0

此空指針快到了由於String array String[] iD = new String[150];所有成員不初始化例如for循環被填充此ID數組或者未運行,直到150或它的一個成員與空,因此

首先初始化打印並檢查nNumStudents的值應爲150.然後確保分配給iD數組的每個值都是非空值,可以通過修改代碼來打印分配給它的所有值來執行此操作。

for(int i = 0; i < nNumStudents; i++) //add ID numbers to array iD 
    { 
     iD[i] = srStudents[i].getStudentKey(); 

     //uncomment the below line and see if it doesn't print null 

     System.out.println(srStudents[i].getStudentKey()); 
    } 

如果它超過150,那麼你將得到一個ArrayIndexoutofbound異常不爲空指針