2015-04-03 29 views
0

當我嘗試測試運行時,我不斷得到第51行的空例外: songs [i] .title = Recording.setTitle(); 該方法似乎被稱爲罰款,那麼爲什麼不是歌曲[我]。標題被設置? 我很新的導航類,所以請原諒,如果這是一個愚蠢的問題。這個錯誤的含義是什麼:java.lang.NullPointerException

import java.util.Scanner; 

class Recording { 
    String title; 
    String artist; 
    String time; 

    String getTitle(){ 
     return title; 
    } 


    String getArtist(){ 
     return artist; 
    } 

    String getTime(){ 
     return time; 
    } 

    static String setTitle(){ 
     Scanner title_input = new Scanner(System.in); 
     System.out.println("What is the title of your recording?"); 
     String title_received = title_input.nextLine(); 
     return title_received; 
    } 

    String setArtist(){ 
     Scanner artist_input = new Scanner(System.in); 
     System.out.println("Who is the artist of your recording?"); 
     String artist_received = artist_input.nextLine(); 
     return artist_received; 
    } 

    String setTime(){ 
     Scanner time_input = new Scanner(System.in); 
     System.out.println("How long is your recording of your recording?"); 
     String time_received = time_input.nextLine(); 
     return time_received; 
    } 
} 
public class RecordingSort { 

    public static void main(String[] args) { 


      Recording[] songs = new Recording[5]; 

      for(int i = 0; i<5; ++i){ 
       songs[i].title=Recording.setTitle(); 
       System.out.println(songs[i].title); 
      } 

    } 

} 
+0

的關鍵是,一個*參考*陣列最初充滿空值。可以認爲它與創建一個蛋盒相似。直到您首先用雞蛋填充紙箱後才能使用任何雞蛋。因此,例如對於您的歌曲數組,首先需要將錄製對象分配給數組中的每個項目,然後才能調用它們的方法。 – 2015-04-03 21:52:40

回答

1

您收到此錯誤,因爲雖然你宣佈和分配5個Recording對象的數組,你從來沒有真正實例化陣列中的任何物體。

嘗試此處添加一行:

for(int i = 0; i<5; ++i){ 
       songs[i] = new Recording(); //invoke a valid object constructor here         
       songs[i].title=Recording.setTitle(); 
相關問題