使用 charAt 方法和类型转换生成字符串中平均字母的输出

Produce an output that is the average letter in the string using charAt method and type-casting

我需要创建一个程序,使用提示读入随机单词。

程序需要生成一个输出,即字符串中的平均字母。

如果字母的平均值为97.2,则显示小a,但如果字母的平均值为97.5,则显示小b。

我需要使用类型转换和作为字符串一部分的 charAt 方法 class

这是关于我必须做的事情的所有信息,我很困惑。我没有任何代码,因为我什至不知道从哪里开始解决这个问题。将不胜感激。

谢谢!非常感谢您的反馈!

这是我的代码post反馈:

public class Average_Of_String {



public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String word;


    System.out.println("say something");
    word = scan.nextLine();

    float sum = 0;
    for(int i = 0; i < word.length(); i += 1) {
        sum += word.charAt(i);
    }

    System.out.println("Sum is " + sum + " and average is " + Math.round(sum/word.length()) + "(" + sum/word.length() + ")");
    int average = (int) (sum/word.length());
    System.out.println((char) average);
}

}

charAt函数returns一个字符。 Ascii Table 状态:

an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort

在该站点上,您可以看到 a 等于十进制 97

试试这个,代码简单明了:

class Average {
  public static void main(String[] args) {
    String word = args[0]; // let us suppose you get the word this way
    float sum = 0;
    for(int i = 0; i < word.length(); i += 1) {
      sum += word.charAt(i);
    }

    System.out.println("Sum is " + sum + " and average is " + Math.round(sum/word.length()) + "(" + sum/word.length() + ")");
  }
}