数组不会使用小句子

时间:2014-03-05 18:19:38

标签: java arrays word-count variable-length

如果我将文本更改为两个单词,程序将不会输出任何内容。不知道如何解决这个问题,提前谢谢。

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 个答案:

答案 0 :(得分:1)

您需要遍历所有wordLengthCount

快速修复:

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

Live demo