【发布时间】:2012-12-08 09:28:45
【问题描述】:
我正在编写一个程序来查找文本中最常用的 10 个单词,但我遇到了困难,不知道下一步该怎么做。有人可以帮帮我吗?
我只走了这么远:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Lab4 {
public static void main(String[] args) throws FileNotFoundException {
Scanner file = new Scanner(new File("text.txt")).useDelimiter("[^a-zA-Z]+");
List<String> words = new ArrayList<String>();
while (file.hasNext()){
String tx = file.next();
// String x = file.next().toLowerCase();
words.add(tx);
}
Collections.sort(words);
// System.out.println(words);
}
}
【问题讨论】:
-
一个
List的单词是不够的,你还需要一个count的每个单词出现。你会为这样的任务使用什么数据结构? (显然,这是作业,这就是我提出这个问题的原因) -
我认为您阅读文件的方式存在错误。 file.next() 最终会为空,所以你应该检查一下。
标签: java