Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...