【发布时间】:2016-03-26 08:27:24
【问题描述】:
对于一个作业,我被要求将一个 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());
}
任何关于从这里去哪里的建议将不胜感激。
【问题讨论】: