数组不会使用小句子

时间:2021-09-04 07:14:07

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

1 个解决方案

#1


1  

You need to iterate over all wordLengthCount

您需要遍历所有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

现场演示

#1


1  

You need to iterate over all wordLengthCount

您需要遍历所有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

现场演示