gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:57:32 25 4
gpt4 key购买 nike

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

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

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

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

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

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

这是我的代码发布反馈:

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

}

最佳答案

试试这个,代码简单且不言自明:

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() + ")");
}
}

关于java - 使用 charAt 方法和类型转换生成字符串中平均字母的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52909593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com