Java 计算X字母单词的频率?

Java 计算X字母单词的频率?,java,algorithm,Java,Algorithm,我必须创建一个程序,计算X字母单词的频率/出现次数,我已经让程序计算出单词的频率和长度,但现在我需要计算出输入单词的平均长度,我真的被困在这个问题上,因此如果有人能帮我,我将不胜感激 这是我目前拥有的代码: import javax.swing.JOptionPane; public class CountLetters { public static void main( String[] args ) { String input = JOptionPane.showInputDia

我必须创建一个程序,计算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 ); 
}
}
平均值就是totalValue/totalCount

要将其作为现有代码末尾的另一个循环执行,请执行以下操作:

从0开始

long totalValue = 0;
long totalCount = 0;
因此,您需要循环计算所有字数,执行以下操作:

totalValue += wordLength * wordCount;
totalCount += wordCount;
最后你只需要做:

float mean = (float)totalValue/totalCount;
或者,在执行主循环的同时计算平均值,您可以执行以下操作:

totalValue += wordLength;
totalCount += 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 );
    }

你能肯定这一点吗?如果你有100个单词,3个字母长,而没有其他内容,那么你的算法的平均值将为0.03…@dan仍然错误,不幸的是:你需要将键和值相乘。“看我的答案!”TimB又打电话给我我写了一个测试,事实上你是对的。但是这个代码没有计算平均值?这是在计算平均数?对不起,我的错,这是一个四舍五入的整数。如果需要,我如何阻止它这样做,并给出一个小数点?我在答案中添加了这一点作为第二个选项。我已将上面的代码编辑为我尝试过的代码,但返回时出现错误?