【问题标题】:Array wont work with small sentences数组不适用于小句子
【发布时间】:2014-04-07 23:54:05
【问题描述】:

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

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

【问题讨论】:

  • WFM,输出两行:“1,长度为2”和“5,长度为3”,现场证明:ideone.com/cl4o5V
  • 尝试将字符串更改为“Hello there!”不会有输出。谢谢

标签: java arrays word-count variable-length


【解决方案1】:

你需要遍历所有wordLengthCount

快速修复:

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

Live demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    相关资源
    最近更新 更多