对于作业,我被要求将txt文档预处理到hashmap中,以便拥有有效的单词搜索功能。 “为了实现高效的单词搜索,您的代码会对文档进行预处理,并将文档中找到的所有单词以及找到它们的行存储在哈希表中(单词是键,行是值)。”我无法弄清楚我的生活,为什么我无法用钥匙替换钥匙的新值。这是预处理文档的构造函数。
HashMap<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();
public wordSearch() {
char charChecker;
String word;
ArrayList<Integer> count = new ArrayList<Integer>();
try{
URL url = new URL("http://homes.soic.indiana.edu/classes/spring2016/csci/c343-yye/docu.txt");
Scanner in = new Scanner(url.openStream());
int lineNumber = 1;
while(in.hasNext()) {
String str = in.nextLine();
for(int i = 0; i < str.length(); i++) {
for(int j = i+1; j < str.length(); j++) {
charChecker = str.charAt(j);
//check for word
if(charChecker == ' ' ||
charChecker == ',' ||
charChecker == '.' ||
charChecker == '\n') {
word = str.substring(i, j);
//if word is already in HashMap
if(this.map.containsKey(word)) {
count = this.map.get(word);
count.add(lineNumber);
//System.out.println("[" + word + ", " + count.toString() + "]");
this.map.put(word, count);
}
//otherwise add word to HashMap
else {
count.add(lineNumber);
System.out.println(count.toString());
this.map.put(word, count);
//System.out.println("[" + word + ", " + count.toString() + "]");
}
i = j+1;
count.clear();
}
}
}
lineNumber+=1;
}
in.close();
}catch(IOException e) {
System.out.println(e.getMessage());
}
System.out.println(this.map.toString());
}
任何关于从何处出发的建议都将不胜感激。
答案 0 :(得分:1)
而不是count.clear();
使用count = new ArrayList<Integer>();
现有代码具有相同的所有键计数实例
答案 1 :(得分:0)
另一种方法是检查一个单词的行号是否存在。
HashMap<String, List<Integer>> wordMap = new HashMap<>();
List<Integer> lineNumbers;
if(...){
word = str.substring(i, j);
if ((lineNumbers = wordMap.get(word)) != null){
lineNumbers.add(lineNumber);
}else {
lineNumbers = new ArrayList<>();
lineNumbers.add(lineNumber);
wordMap.put(word, lineNumbers);
}
i = j+1
}