计数第X字母词的频率是多少? [英] Count the Frequency of X letter words?
本文介绍了计数第X字母词的频率是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要创建一个程序,它计算的x的单词字母的频率/发生,我已经得到了计划制定出单词的频率和长度,但现在我需要计算出的平均长度进入的话,我真的卡在这,所以如果有人可以帮助我将不胜感激
i have to create a program where it counts the frequency/occurrence of X letter of words, i have got the program to work out the frequency of the words and the lengths but now i need to work out the mean length of the words entered, i am really stuck on this so if anyone can help i will be grateful
这是在code,我有作为尚未:
This is the code i have as of yet:
import javax.swing.JOptionPane;
public class CountLetters {
public static void main( String[] args ) {
String input = JOptionPane.showInputDialog("Write a sentence." );
int amount = 0;
String output = "Amount of letters:\n";
for ( int i = 0; i < input.length(); i++ ) {
char letter = input.charAt(i);
amount++;
output = input;
}
output += "\n" + amount;
JOptionPane.showMessageDialog( null, output,
"Letters", JOptionPane.PLAIN_MESSAGE );
}
}
推荐答案
使用一个映射到字长度映射到字长发生的次数。
Use a map to map the word length to the number of times that word length occurs.
然后按照添B的回答乘法逻辑。
Then follow the multiplicative logic of Tim B's answer.
一个简单的例子我扔在一起。
A quick example I threw together.
public static void main(final String[] args) {
final Map<Integer, Integer> wordLengths = new HashMap<Integer, Integer>();
final String testString = "the quick brown fox jumped over the lazy dog";
final String[] words = testString.split(" ");
for (int i = 0; i < words.length; i++) {
final int wordLength = words[i].length();
if( wordLengths.keySet().contains( wordLength ) ) {
Integer currentNumberOfOccurences = wordLengths.get(wordLength);
currentNumberOfOccurences++;
wordLengths.put(wordLength, currentNumberOfOccurences);
continue;
}
wordLengths.put(wordLength, 1);
}
double totalLength = 0;
double totalOccurrences = 0;
for (final Integer length : wordLengths.keySet()) {
final Integer occurrences = wordLengths.get(length);
totalLength = totalLength + (length * occurrences );
totalOccurrences += occurrences;
}
final double mean = totalLength / totalOccurrences;
System.out.println("Average word length is: " + mean );
}
这篇关于计数第X字母词的频率是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文