【问题标题】:Making a HashMap from a text file using Buffered Reader?使用缓冲阅读器从文本文件制作 HashMap?
【发布时间】:2018-02-15 19:29:45
【问题描述】:

我在编码一个给定参数的方法时遇到了问题,一个文件名,读取包含单词的文件并制作一个以键作为第一个字母的哈希图,例如对于文件中的单词,例如 apple ,'a' 是键,值是 'apple'。

我目前拥有的代码:

public class WordStore {
HashMap<String, List<String>> map;
File filename;

public WordStore() {
     map = new HashMap<String, List<String>>();
}

public WordStore(File file) throws IOException {
    map = new HashMap<String, List<String>>();
    BufferedReader br = null;
    //k = "/Users/hon/eclipse-workspace/Assignment4/src/wordbank.txt"
    try{
        File filename = new File(k);
        FileReader fr = new FileReader(filename);
        br = new BufferedReader(fr);    
        while(br.readLine()!=" ") {
        String word ="";
        word = br.readLine();
        String key = ""+(word.charAt(0));
        map.put(key, word);
        }

    }
    catch(IOException e) {
        System.out.println("File not found exception caught!");
    }
    finally {
        if(br != null) {
            try {
                br.close();
            }
        catch(IOException e) {
            e.printStackTrace();
        }
        }
    }

}
public void put(String key, String word) {
    if(map.containsKey(key)) {
        (map.get(key)).add(word);
    }
    else {
    List<String> names = new ArrayList<>();
    names.add(word);
    map.put(key, names);
    }
}
}

我在 map.put(key, word) 的构造函数 WordStore(File file) 中有一个错误,它表示 put(String, List&lt;String&gt;) 类型中的方法 HashMap&lt;String, List&lt;String&gt;&gt; 不适用于参数 (String, String)。

我尝试重命名我的 put 方法,以便它使用我的方法而不是 hashmap put 方法,但这也不起作用。

【问题讨论】:

  • 将地图更改为 map = new HashMap();
  • 你的put方法不是map的方法,调用它只需使用put(key, word);

标签: java hashmap bufferedreader


【解决方案1】:

您正在尝试将 String 值放置在预期 List 的位置。这是因为你调用了map 的普通put 方法。改为调用您自己的 put 方法,它已经处理了列表。

put(key, word);

另外,您从文件中读取的方式也不正确。首先,您将字符串与不正确的 != 进行比较。然后,每个循环调用两次 readLine。循环的顶部应该是:

String word;
while( (word = br.readLine() ) != null) {

这会读取一行并将其与同一行中的null 进行比较以测试文件结束。

【讨论】:

  • 感谢您的帮助和简单明了的解释。
【解决方案2】:

您创建了put 方法,这没关系,但您不调用它。 相反,您使用map 的“原始”put 方法。

因此将map.put 的第一个实例更改为put

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    相关资源
    最近更新 更多