java - 平均字长

标签 java loops printing while-loop enter

我试图以一种非常简单的方式计算 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/

相关文章:

java - 双向链表,在Java中的给定节点之前插入

java - 将内容导入到分配的 ByteBuffer 中

c++ - 什么相当于C/C++中C#的PrintDocument?

c++ - 有没有用 C++ 编写的开源 PDF 打印机?

python - 在 Python 中循环遍历多波段栅格中的每个像素

css - 打印样式表 - Webkit 与 Gecko/IE 中的打印页面宽度不同

java - 对话框在主 Activity 中触发非静态方法

java - 获取错误 : java. lang.IllegalArgumentException:不是有效的域名:jhipster uaa 项目中的 '192.168.0.202'

Python 按两列或更多列进行分组

java - while 循环不退出