2 回答
TA贡献1810条经验 获得超4个赞
你的逻辑有点不对。当您阅读next()then 时nextLine(),nextLine()将不包括所阅读的内容,next()因此您每次迭代都会跳过一个单词。试试这个:
- 用useDelimiter();读到句号、感叹号或问号(句末)的方法读一行
使用 a.作为分隔符的示例:
Scanner in = new Scanner("Hello. This is a string. It has multiple senteces").useDelimiter("\\.");
while(in.hasNext()) {
System.out.println(in.next());
}
- 将句子添加到句子中 ArrayList()
- 将句子拆分为单独的单词并将它们添加到单词中 ArrayList()
TA贡献1829条经验 获得超13个赞
下次给我们更多关于你的任务的细节,这样我们就不必猜测了:)
无论如何,请使用以下结构来阅读每个句子:
Scanner sc = new Scanner(inputFile).useDelimiter("\.");
while (sc.hasNext()) {
// we will hold your sentence in the s variable
Sting s = sc.next();
// here you add the string to your sentence array
// or better be conscious about your memory usage
// and do the processing right away.
processSentence(s);
}
从您的代码片段看来,您似乎需要收集有关您的字数和最流行词的统计信息。HashMap<String, Integer>将是很好的结构。
void processSentence(String s) {
Scanner ws = new Scanner(s).useDelimiter(" ");
while (ws.hasNext()) {
Sting w = ws.next();
// I assume you have this.wordCounters initialized as HashMap<String,Integer>();
Integer c = this.wordCounters.get(w);
if (c==null) { c=0; }
c = c+1;
this.wordCounters.put(w, c);
}
}
添加回答
举报