gpt4 book ai didi

java - 数组不适用于小句子

转载 作者:行者123 更新时间:2023-12-01 13:18:58 25 4
gpt4 key购买 nike

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

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

关于java - 数组不适用于小句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22205968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com