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



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

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

如果字母的平均值为 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() + ")");
}
}

charAt函数返回一个字符。ASCII表指出:

ASCII 码是字符的数字表示形式,例如 "a"或"@"或某种操作

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

最新更新