如果我将文本更改为两个单词,程序将不会输出任何内容。在此之前,没有关于如何解决此问题的线索。

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);
 }
}

最佳答案

您需要遍历所有wordLengthCount

快速解决:

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


Live demo

10-07 16:43