java基于每个字母的ASCII值的句子中的平均单词值
我想根据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++;
}
}
}
}
如果有人能帮我一个好的逻辑,我将不胜感激
# 1 楼答案
检查此代码。这比你的要简单一点。它对每个单词进行平均,然后对平均值进行平均
# 2 楼答案
实现这一目标的简单方法是这样做:
测试