2012-02-27 48 views
0

所以我在小時結束合作,想出這個代碼HashMap中沒有充分閱讀

public class instructorIO 
{ 
    static Map<String, String> instructors; 


    public static Map<String, String> getInstructors() 
    { 
     try 
     { 
      BufferedReader in = new BufferedReader(new FileReader("instructor.txt")); 

      instructors = new LinkedHashMap<String, String>(); 

      String line; 

      while(((line = in.readLine()) != null)) 
      { 
       line = in.readLine(); 
       String[] val = line.split("<>"); 
       String ID = val[0]; 
       String name = val[1]; 

       instructors.put(ID, name); 
      } 
      in.close(); 
     } 
     catch(IOException ioe) 
     { 
      ioe.printStackTrace(); 
     } 

     return instructors; 
    } 
} 

當我嘗試在我的文本區域來顯示所有的HashMap的值,只有哈希標識顯示2,6和4。總共有6個......我做錯了什麼?我得到一個例外線程「主」java.lang.NullPointerException 在字符串[] val = line.split(「<>」);我不知道這是什麼意思。

+0

「只顯示散列ID 2,6和4」 - 如果文件只有2,4和6個鍵,則這可以正常工作。請記住,hashmaps每個鍵只能有一個值。無論如何,你可以發佈你的文件內容嗎? – m0skit0 2012-02-27 11:17:30

回答

1

您正在閱讀的同時兩條線,只取第二個:

 while(((line = in.readLine()) != null)) 
     { 
      line = in.readLine(); 
      String[] val = line.split("<>"); 
      String ID = val[0]; 
      String name = val[1]; 

      instructors.put(ID, name); 
     } 

曾經在while狀態,再次循環體內。我建議你做這樣的:

 while(((line = in.readLine()) != null)) 
     {     
      String[] val = line.split("<>"); 
      String ID = val[0]; 
      String name = val[1]; 

      instructors.put(ID, name); 
     } 
+0

你能幫助我如何閱讀第1行嗎? – cataschok 2012-02-27 11:17:42

+0

@ user1234587:我添加了一個更正的版本。 – Tudor 2012-02-27 11:18:10

+0

omg。非常感謝!哈哈 – cataschok 2012-02-27 11:22:37

1

要調用:

線= in.readLine();

兩次。一旦進入while循環和一次。所以你正在跳過其他線路。

0

您在while循環中調用line = in.readLine()方法兩次。