Question

If I change the text to two words the program wont output anything. Not a clue on how to fix this, thanks in advance.

public class test {
public static void main(String args[]) {
    String text = "The cat sat on the mat!"; //Change the string to "Hello there!"
    int wordLengthCount [] = new int [20];
    String wordCountText = "";

    String sentence[] = text.split("[,\\-:\\?\\!\\ ]");

    for (int i = 0; i < sentence.length; i++)
    {
        wordLengthCount[sentence[i].length()]++;
    }

    for(int wordLength=0; wordLength<sentence.length; wordLength++)
    {
        if (wordLengthCount[wordLength] != 0){
            wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
        }
    }
    System.out.println(wordCountText);
 }
}
Was it helpful?

Solution

You need to iterate over all wordLengthCount

Quick fix:

for (int wordLength = 0; wordLength < wordLengthCount.length; wordLength++) {
    if (wordLengthCount[wordLength] != 0) {
        wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
    }
}

Live demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top