Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

java - Count the Frequency of X letter words?

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

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:
";

    for ( int i = 0; i < input.length(); i++ ) {
        char letter = input.charAt(i);
        amount++;
        output = input;
    }
    output += "
" + amount;
    JOptionPane.showMessageDialog( null, output,
                         "Letters", JOptionPane.PLAIN_MESSAGE ); 
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The mean is just totalValue / totalCount.

To do it as another loop at the end of your existing code:

Start with them both at 0.

long totalValue = 0;
long totalCount = 0;

So you need to loop through all of your word counts doing:

totalValue += wordLength * wordCount;
totalCount += wordCount;

Then at the end you just do:

float mean = (float)totalValue/totalCount;

Alternatively to calculate the mean at the same time as doing the main loop you can do:

totalValue += wordLength;
totalCount += 1;

Each time around the main loop once you have found a word.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...