有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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++;
    }
    }
    }
    }

如果有人能帮我一个好的逻辑,我将不胜感激


共 (2) 个答案

  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);
        }
    }
    
  2. # 2 楼答案

    实现这一目标的简单方法是这样做:

    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