我正在尝试制作一个计算字符串中单词出现次数的应用程序。例如,如果我有字符串“我想要,因为我想要”,我希望看到结果“ 2,2,1”。
但是我得到的结果是“ 1,1,1,1,1”。
这是我程序的一部分,我认为这是错误的,并且与问题相关:
Scanner counter = new Scanner(text);
int currentword = 0;
String[] thewords = new String[10001];
int[] thenumbers = new int[10000];
String usedwords = "";
while (counter.hasNext()) {
String nextstring = counter.next();
for(int temp = 0; temp < thewords.length;temp++) {
if (thewords[temp] == null) {
thewords[currentword] = nextstring;
currentword++;
thenumbers[currentword]++;
break;
}
else if (thewords[temp].equals(nextstring)) {
thenumbers[temp]++;
break;
}
}
}
为什么我会得到错误的结果的任何想法,因为我已经多次遍历了代码但没有成功发现问题。
任何帮助表示赞赏...
谢谢
最佳答案
有很多方法可以将单词数组简化为单词频率图。这是一个:
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
String text = "I want because I want";
String[] words = text.split("\\s+"); // split by whitespace
Set<String> uniqueWords = Arrays.stream(words).collect(Collectors.toSet());
final Map<String, Long> wordFrequencies = uniqueWords.stream()
.collect(
Collectors.toMap(
Function.identity(),
word -> Arrays.stream(words).filter(w -> w.equals(word)).count()));
wordFrequencies.forEach((word, frequency) -> {
System.out.println(String.format("%s: %d", word, frequency));
});
此代码输出:
want: 2
I: 2
because: 1
关于java - 我的字数统计程序得到错误的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58825737/