我试图以一种非常简单的方式计算 Java 中用户输入的平均字长。我已经完成了代码的实际“数学”,并且它似乎工作得很好,但是为了完成代码,我需要解决一些奇怪的内务问题。
到目前为止,我有以下内容:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
int count = 0;
double sum = 0;
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
double average = 0;
if (count > 0) {
average = sum / count;
}
System.out.println("Average word length = " + average);
}
}
}
最终结果输出应如下所示:
run:
Please type some words, then press enter:
this is a test
Average word length = 2.75
BUILD SUCCESSFUL (total time: 10 seconds)
但是,输出如下所示:
run:
Please type some words, then press enter:
this is a test
Average word length = 4.0
Average word length = 3.0
Average word length = 2.3333333333333335
Average word length = 2.75
根据我编写的代码,我该如何更改它以便:
- “平均字长”仅最后打印一次。
- 用户按回车键后程序结束
感谢您的任何建议。
最佳答案
您每次输入单词时都会计算平均值,这不是您想要的。此外,即使按下 Enter 键,while 循环也会继续。试试这个:
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
int count = 0;
double sum = 0;
String input = sc.nextLine();
String[] words = input.split("\\s+"); // split by whitespace
// iterate over each word and update the stats
for (String word : words) {
double wordLength = word.length();
sum += wordLength;
count++;
}
// calculate the average at the end
double average = 0;
if (count > 0) {
average = sum / count;
}
System.out.println("Average word length = " + average);
输出:
Please type some words, then press enter:
this is a test
Average word length = 2.75
关于java - 平均字长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587675/