我想根据 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/