如果我将文本更改为两个单词,则程序不会输出任何内容。不知道如何解决此问题,请提前。
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";
}
}
实时演示