2016-09-25 35 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