gpt4 book ai didi

java - 基于每个字母的 ASCII 值的句子中的平均单词值

转载 作者:行者123 更新时间:2023-11-30 02:31:55 25 4
gpt4 key购买 nike

我想根据 ASCII 值计算每个单词的平均值例如:你好,H= 72,e= 101,l= 108,l = 108,o = 111
求和得到 500,然后根据字母数计算平均值,即 500/5 =100 因此,Hello 的平均值 = 100,“World”的平均值相同,依此类推。最后计算所有单词的平均值,将其相加并显示为整个句子的最终平均值这是我创建的代码,但它在线程“main”java.lang.ArrayIndexOutOfBoundsException 中给出了异常

   import java.util.*;
import java.lang.*;
import java.io.*;
class Word
{
public static void main (String[] args)
{

String str="Hello World";
int average1=0;
int j=0;
int[] average=new int[20];
String[] s=str.split(" "); //Splitting into each word
for(String s1 : s)
{
char[] c=s1.toCharArray();
for(int i=0;i<str.length();i++)
{
average[i]=(int)c[i]; //Average ASCII based value for each word
}
while(average[j]!=0)
{
average1=average[j]/s1.length(); //Sum up average of each Word and average of who words is calculated
System.out.print(average1);
j++;
}
}
}
}

如果有人能帮我提供良好的逻辑,我将不胜感激。

最佳答案

实现这一目标的一个简单方法是执行以下操作:

public class WordAverage{
public static void main (String[] args) {

String str="Hello World";
double average=0; // you need only one double variable, why double -> because of the division later
// note that if you don't want the decimal you can change it to int
for(char c : str.toCharArray()){ // cycle through every char in the String
if(c!=' '){ // if it is not a space
average += (int)c; // sum its value
}
}

average /= str.replace(" ", "").length(); // then divide the average value by the String length after removing the spaces (if any)
System.out.println(average);
}
}

测试

Hello World     -> 102.0
How Are You? -> 96.2
Fine Thank You! -> 95.23

关于java - 基于每个字母的 ASCII 值的句子中的平均单词值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44087234/

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