2012-11-04 44 views
2

我正在編寫一個程序,用於輸入需要安排的各種講座請求。 講座有開始時間和結束時間。 要求是安排最大數量的講座。 (該算法是在結束時間安排它們並選擇非重疊講座 - 貪婪策略)。 爲了做到這一點,我有一個「講座」班和一個「講座調度」班。 我創建了一個輸入數組(講座)。然後我要求用戶輸入各種請求。 但是我收到錯誤「線程中的異常」main「java.lang.NullPointerException」。 請幫忙。 謝謝。 PS: 我在線「input [i] .time [0] = in.nextInt();」 確切的錯誤是:在lecturescheduling.LectureScheduling.main(LectureScheduling.java:116)在螺紋 異常 「主」 顯示java.lang.NullPointerException 即使初始化數組時,空指針異常

//講座類..時間[0]是開始時間和時間[1]是演講的結束時間

class lecture{ 
    int[] time= new int[2]; 

    lecture (int a, int b){ 
      time[0]=a; 
      time[1]=b;   
    } 
} 

// LectureScheduling類的一部分

public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    System.out.println("Input number of lectures "); 
    int arraylength = in.nextInt(); 
    lecture [] input= new lecture[arraylength] ; 
    for (int i=0; i<arraylength; i++){ 
     System.out.println("Input start time of lecture "+ i); 
     input[i].time[0] = in.nextInt();   
     System.out.println("Input end time of lecture "+ i); 
     input[i].time[1] = in.nextInt();   
     System.out.println(); 
    } 
    input=SortByStartTime(input); 
    input=CreateSchedule(input); 
    PrintSchedule(input); 
} 

回答

6

當分配對象的數組時,實際上是僅分配的引用,而不是對象本身(lecture [] input= new lecture[arraylength] ;不會創建類型爲lecture的對象,這與值類型語言(如C++)不同)。因此,當你訪問:

input[i].time[0] = in.nextInt(); 

沒有先爲input[i]創建lecture一個實例,你就會得到一個NPE。

爲了解決它,你需要您嘗試訪問之前使用new運營商的lecture每個對象(假設空的構造是可見的,定義):

input[i] = new lecture(); 

附:在java中有一個類型名稱的約定(如lecture,這是一種類型) - 以大寫字母開頭。所以我建議將lecture重命名爲Lecture

+0

因此,這意味着在for循環中,我將首先初始化輸入[i],然後接受輸入? –

+0

@ user1683651:是,或作爲預處理,在不同的for循環中(在訪問數據的for循環之前) – amit

+0

,有很多幫助。 –