2012-01-20 13 views
1

私は以下の方法で地図にファイルをロードしようとしています:java内のマップ上のNullPointerException。なにが問題ですか?

private static Map<String,Integer> indexVocabulary; 
public static Map<String,Integer> getVocabularyFromFile() throws IOException 
{ 
    FileInputStream fstream = new FileInputStream(VOCABULARY_FILE); 
    DataInputStream in = new DataInputStream(fstream); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in));  
    String line; 
    while((line = br.readLine()) != null) 
    { 
     LOG.debug(line); 
     String[] kv = line.split(" "); 
     LOG.debug(kv[0]); 
     LOG.debug(Integer.toString(Integer.parseInt(kv[1]))); 


     indexVocabulary.put(kv[0], Integer.parseInt(kv[1])); 
    } 
    return indexVocabulary; 
} 

私はラインindexVocabulary.put(kv[0], Integer.parseInt(kv[1]));にNullPointerExceptionが取得しかし、私はkv[0],kv[1]とからも」lineからの出力を見ることができ、誰もが何を知っていますこの方法は間違っていますか?

答えて

8

それはnullですのであなたは、indexVocabularyを初期化しません。

private static Map<String,Integer> indexVocabulary = new HashMap<String,Integer>(); 
+5

ランダムなダウンボードが再び襲います! – NPE

3

indexVocabularyの初期化を忘れました。

ちょうど行います

indexVocabulary = new HashMap<String, Integer>(); 
3

変更

private static Map<String,Integer> indexVocabulary; 

あなたはindexVocabularyに任意のオブジェクトを代入していないので、それはnullです。

private static Map<String,Integer> indexVocabulary = new HashMap<String,Integer>; 
3

マップをインスタンス化していません。だから、単にあなたの地図を初期化できませんでした

indexVocabulary = new HashMap<String,Integer>();

4

を入れて、それだけで空の変数です。地図をインスタンス化する必要があります。たとえば、次のようにすることができます。

indexVocabulary = new HashMap<String,Integer>(); 
関連する問題