我必须创建一个程序,它计算X字母的频率/出现次数,我有程序计算单词的频率和长度,但现在我需要计算出的平均长度进入的话,我真的被困在这,所以如果有人可以帮助我将感激不尽
这是我迄今为止的代码:
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 );
}
}
答案 0 :(得分:1)
平均值只是totalValue / totalCount
。
将其作为现有代码末尾的另一个循环:
从0开始。
long totalValue = 0;
long totalCount = 0;
所以你需要遍历所有的字数:
totalValue += wordLength * wordCount;
totalCount += wordCount;
然后在结束时你就做了:
float mean = (float)totalValue/totalCount;
或者,在执行主循环的同时计算平均值,您可以这样做:
totalValue += wordLength;
totalCount += 1;
一旦你找到一个单词,每次都围绕主循环。
答案 1 :(得分:1)
使用地图将字长映射到字长发生的次数。
然后按照Tim B回答的乘法逻辑。
我拼凑的一个简单例子。
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 );
}