【发布时间】: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<String>) 类型中的方法 HashMap<String, List<String>> 不适用于参数 (String, String)。
我尝试重命名我的 put 方法,以便它使用我的方法而不是 hashmap put 方法,但这也不起作用。
【问题讨论】:
-
将地图更改为 map = new HashMap
(); -
你的
put方法不是map的方法,调用它只需使用put(key, word);
标签: java hashmap bufferedreader