How to find the average of words using the characters of the JTextArea inputted string

Kiana :

I am writing a program for an assignment using JTextArea to have the user manually input text then I/the program computes simple statistics. The problem I am having is when I'm computing the average length of each word inputted, it does not compute correctly (ie: words: 2, characters: 6, average length: 3, but my program currently says 3.5).

I've tried (double) and (float) and nothing in front of (count++)/words.length to see if it was the program's rounding errors and that doesn't effect the output at all.

I also thought it might be because it is count the spaces ' ' so I found on a snippet of code that excludes the space in counting the characters of the inputted string. @ https://www.quora.com/How-do-I-count-characters-in-a-string-in-Java-without-using-charcount

I'm still fairly new to Java, and help would be appreciated! I feel like it's a simple solve, just something I'm not seeing yet. I've include the part of the code that pertains to this, and everything not included is me creating the text field, frame, and buttons, etc...

public void actionPerformed(ActionEvent event){

        String parsedString = inputText.getText();
        String delims = "[1234567890.,?!()*\\s]+";
        String words[]=parsedString.split(delims);

        char [] ch = parsedString.toCharArray();
        int count=0;
        for (int i = 0; i < ch.length; i++) {
            if (ch[i]!=' '){
            count++;
            }
        }

        wordCounter.setText("Words inputed: " + words.length);
        wordCharacters.setText("Characters:" + count++ );
        wordAverage.setText("Average Length: " + (float) (count++)/words.length ); 

    }
Anuradha :

You need to trim the parsedString before use it in the code. It removes leading and trailing spaces in the string.

Here wordCharacters.setText("Characters:" + count++ ); and wordAverage.setText("Average Length: " + (float) (count++)/words.length ); here count++ is unnecessary because it increments the count calculated from for loop. It is the issue in your code. Please check below answer.

public void actionPerformed(ActionEvent event) {
    String parsedString = inputText.getText().trim();
    String delims = "[1234567890.,?!()*\\s]+";
    String[] words = parsedString.split(delims);

    char[] ch = parsedString.toCharArray();
    int count = 0;
    for (int i = 0; i < ch.length; i++) {
        if (ch[i] != ' ') {
            count++;
        }
    }
    wordCounter.setText("Words inputed: " + words.length);
    wordCharacters.setText("Characters:" + count);
    wordAverage.setText("Average Length: " + (float) (count) / words.length);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=347462&siteId=1