繁体   English   中英

将元素添加到哈希图的值数组时出现错误

[英]Getting error when adding element to value array of hashmap

我有一个正在读取的文本文件。 我的目标是为文本文件中每个单词创建一个哈希图,并在其中显示索引。 索引定义为文本的一部分。 在这种情况下,每100个字符被视为一个索引。 出于某种原因,当我尝试向数组添加索引时出现错误。 该错误显示“找不到符号”。 我对Java很陌生,因为我昨天才开始在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);
    }
}

//您需要将hm.get(x)类型转换为ArrayList,例如

((ArrayList)hm.get(x))。add(页面);

您需要更改:

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

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

如果您未定义地图类型,则get()返回一个Object 通过定义Map<String,ArrayList<Integer>> get将返回ArrayList<Integer>>


使用ArrayList<Integer>而不是ArrayList<String>因为您将整数而不是字符串存储在arraylist中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM