我想根据ASCII值计算每个单词的平均值
对于EX:你好,H = 72,e = 101,l = 108,l = 108,o = 111
总结它将给出500,然后根据字母数计算平均值,即500/5 = 100因此平均值= 100,平均值为"世界"等等 。
最后计算所有单词的平均值,总结并显示为整句的最终平均值
这是我创建的代码,但它在线程" main"中给出了一个Exception。 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++;
}
}
}
}
如果有人可以用一个好的逻辑来帮助我,那将是非常感激的。
答案 0 :(得分:1)
实现这一目标的一种简单方法是做这样的事情:
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
答案 1 :(得分:1)
检查此代码。这比你的简单一点。它平均每个单词,然后平均平均值。
import java.util.*;
import java.lang.*;
import java.io.*;
class Word
{
public static void main (String[] args)
{
String str="Hello World";
String[] s = str.split(" ");
int[] average = new int[s.length];
for(int i = 0; i<s.length; i++) {
int wordAverage = 0;
System.out.println(s[i]);
for(int j=0;j<s[i].length(); j++) {
wordAverage += (int)s[i].charAt(j); //Average ASCII based value for each word
}
average[i] = wordAverage/s[i].length();
System.out.println(average[i]);
}
int finalAverage = 0;
for(int i = 0; i<average.length; i++)
finalAverage += average[i];
finalAverage/=average.length;
System.out.println(finalAverage);
}
}