2016-09-25 40 views
0

我有一個正在閱讀的文本文件。我的目標是創建一個文本文件中每個單詞的散列表,並在其中出現索引。索引被定義爲文本的一部分。在這種情況下,每100個字符被認爲是一個索引。出於某種原因,當我嘗試將索引添加到數組時,出現錯誤。錯誤說「找不到符號」。我對java很陌生,因爲我昨天剛剛開始編寫代碼,所以任何幫助都會很感激。我的代碼如下:將元素添加到哈希映射的值數組時遇到錯誤

import java.io.*; //needed for File class below 
import java.util.*; //needed for Scanner class below 

public class readIn { 

    public static void readInWords(String fileName) { 
     try { 
      //open up the file 
      Scanner input = new Scanner(new File(fileName)); 
      HashMap hm = new HashMap<String, ArrayList<String>>(); // Tells Java What datatypes are in the hashmap hm 
      //Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>(); 
      int length = 0; 
      int total = 0; 
      int page = 0; 
      while (input.hasNext()) { 
       //read in 1 word at a time and increment our count 
       String x = input.next(); 
       if (total < 100) { 
        length = x.length(); 
        total = total += length; 
       } else { 
        total = 0; 
        page++; 
       } 
       if (hm.get(x) == null) { 
        hm.put(x, new ArrayList<Integer>(page)); 
       } else { 
        hm.get(x).add(page); 
       } 

      } 
      System.out.println(length); 
      System.out.println(hm); 
     } catch (Exception e) { 
      System.out.println("Something went really wrong..."); 
     } 
    } 

    public static void main(String args[]) { 
     int x = 10; //can read in from user or simply set here 

     String fileName = "test.txt"; 
     readInWords(fileName); 
    } 
} 
+0

你能指定錯誤發生在哪一行嗎? – engineercoding

+0

當然,它在第28行。「hm.get(x).add(page)」 – mangodreamz

+3

你的代碼有太多問題,但是你的具體編譯器錯誤可以通過改變'HashMap hm = new HashMap >();'to'HashMap > hm = new HashMap >();' –

回答

0

//你需要強制類型轉換hm.get(X)爲一個ArrayList像

((ArrayList的)hm.get(X))加(頁)。

0

你需要改變:

HashMap hm = new HashMap<String, ArrayList<String>>(); 

Map<String,ArrayList<Integer>> hm = new HashMap<String, ArrayList<Integer>>(); 

如果不定義地圖類型,get()返回Object。通過定義Map<String,ArrayList<Integer>>獲取將返回一個ArrayList<Integer>>


使用ArrayList<Integer>而不是ArrayList<String>,因爲您將整數存儲在arraylist中,而不是字符串。

+0

反饋將不勝感激。 – c0der