gpt4 book ai didi

java - 查找单个字符串中每个单词的平均字符数

转载 作者:行者123 更新时间:2023-11-29 03:35:58 25 4
gpt4 key购买 nike

我有点卡在这个问题上了。我试图在一个字符串中存储 1 个或多个单词,找到所有单词的组合长度,然后将其除以单词数以找到平均值。我需要在 while 循环中执行此操作(这是作业的目标)

当我输入“Hello my name is”时,它返回长度为

Result:  
5
2
4
2

但我想要的是将这些结果相加然后除以字数

5+2+4+2 = 13  
13/4 = 3.25

这是我目前所拥有的:

Scanner in = new Scanner(System.in);

int counter = 0;
double sum = 0;

while (in.hasNext()) {
String word = in.next();
double totalchar = word.length();
sum = totalchar + sum;
counter++;


double average = 0;
if (counter > 0) {
average = sum / counter;

}
System.out.println(average);
}

最佳答案

只需将average 计算和打印移到while 循环之外:

while (in.hasNext()) {
String word = in.next();
if (word.equals("exit")) {
break;
}
double totalchar = word.length();
sum = totalchar + sum;
counter++;
}
double average = 0;
if (counter > 0) {
average = sum / counter;
}
System.out.println(average);

关于java - 查找单个字符串中每个单词的平均字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15563756/

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