2013-10-11 122 views
0

我得到這個錯誤NullPointerException異常和NoSuchElementException異常

java.lang.NullPointerException 
    at MidiPlayer.add_midi_files(MidiPlayer.java:59) 
    at MidiPlayer.main(MidiPlayer.java:51) 
Songs added! 
Starting to play 
Exception in thread "main" java.util.NoSuchElementException 
    at java.util.LinkedList.removeFirst(LinkedList.java:268) 
    at java.util.LinkedList.remove(LinkedList.java:683) 
    at MidiPlayer.play_next_song(MidiPlayer.java:31) 
    at MidiPlayer.start_playing(MidiPlayer.java:47) 
    at MidiPlayer.main(MidiPlayer.java:54) 

從這些方法

public static void main(String[] args){ 
    Queue<String> song_queue = new LinkedList<String>(); 
    MidiPlayer.add_midi_files(song_queue,new File("C:\\Users\\Kyle\\Desktop\\clieent\\Client\\cache\\Music\\runescape-7th realm.mid")); 
    System.out.println("Songs added!"); 
    MidiPlayer player = new MidiPlayer(song_queue); 
    player.start_playing(); 
}; 

public static void add_midi_files(Queue<String> queue, File top_dir){ 
    try { 
     for (File f: top_dir.listFiles()) 
      if (f.isDirectory()) 
       add_midi_files(queue, f); 
      else if (f.isFile() && f.getName().matches(".*midi?")) 
      { 
       System.out.println(f); 
       queue.add(f.getAbsolutePath()); 
      } 
      else 
      {} 
     //System.out.printf("%s doesn't match!", f.getName()); 
    } catch (NullPointerException e) { 
     e.printStackTrace(); 
    } 
} 

老實說,我看不出有什麼問題,誰能幫我?

在正確的方向任何提示,將不勝感激

這裏就是整個類,如果你需要它,http://pastebin.com/0hVw83zn

+1

添加文件時,您確定在第51行有正確的文件目錄嗎? – Zeveso

+0

http://stackoverflow.com/questions/18795000/program-throws-nullpointerexception-when-i-try-to-search-in-drives/18795076#18795076 – JNL

回答

4

File#listFiles()可以返回null。見javadoc

,則返回null如果發生I/O錯誤此抽象路徑名不表示一個目錄,或 。

catch聲明燕子NullPointerException然後

player.start_playing(); 

嘗試從Queue,並沒有考慮。