如何使用数组计算文本文件中重复的单词?
我的程序能够打印出文件中的总单词数,但是如何让我的程序打印不同单词的数量,并打印出重复单词的数量列表,如下所示:
蛋糕:4 答:320 件数:2 共 24 条
(大写字母和小写字母的单词被视为同一个单词)
void FileReader() {
System.out.println("Oppgave A");
int totalWords = 0;
int uniqueWords = 0;
String [] word = new String[35000];
String [] wordC = new String [3500];
try {
File fr = new File("Alice.txt");
Scanner sc = new Scanner (fr);
while(sc.hasNext()){
String words = sc.next();
String[] space = words.split(" ");
String[] comma = words.split(",");
totalWords++;
}
System.out.println("Antall ord som er lest er: " + totalWords);
} catch (Exception e) {
System.out.println("File not found");
}
最佳答案
这对于数组来说是非常低效的,因为在每个单词之后,您必须遍历数组以查看该单词是否已经出现。而是使用 HashMap,其中键是单词,值是出现的次数。查看 HashMap 是否包含键比查看数组是否包含元素更容易、更快。
编辑:
HashMap<String, Integer>
关于java - 计算文本文件中唯一单词的数量? (不允许使用Hash),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19927097/