【问题标题】:How to Create a Table of Names and Average Numbers?如何创建名称和平均数字表?
【发布时间】:2021-09-25 15:53:09
【问题描述】:

我需要编写一个从标准输入读取行的 Java 程序 每行包含一个名称和三个整数,然后使用 printf() 打印一个表 一列名称、整数和三个整数的平均值,精确到小数点后两位 地方。我将指定名称的数量作为命令行参数,然后输入 at 至少该数量的名称(以及每个名称的三个整数)。然后我会发出 Control Z 结束的信号,然后 Enter,因为我使用的是 Windows。

我的最终结果应该是这样的: java平均4

乔 3 5 2

蒂姆 4 1 5

1 月 6 日 3 月 2 日

杰克 8 3 5

Ctrl+Z

乔 3 5 2 3.33

蒂姆 4 1 5 3.33

简 6 3 2 3.67

杰克 8 3 5 5.33

现在,我的程序只对我输入的数字求平均。它没有打印我输入的名称。谁能给我有关如何更正当前代码的提示?因为我是编程新手,所以我希望尽可能简单。

    public static void main(String[] args) { 
        String names = args [0];
        
        int count = 0;       // number input values
        double sum = 0.0;    // sum of input values

        // read data and compute statistics
        while (!StdIn.isEmpty()) {
            String run = StdIn.readString ();
            double value = StdIn.readDouble();
            sum += value;
            count++;
        }

        // compute the average
        double average = sum / count;

        // print results
        StdOut.print(names);
        StdOut.printf(names + "%3.2f", average);
    }
}

【问题讨论】:

    标签: java average stdout


    【解决方案1】:

    main(String[] args) 在您第一次启动程序时被调用。如果您在不传递任何参数的情况下启动程序,names 将为空。您需要在启动程序时传入您的姓名,或者在 while 循环中使用 StdIn 填充 names,就像其他值一样。

    【讨论】:

    • 我希望能够在不输入特定名称的情况下生成任何名称。我是否需要为此使用数组,或者对我当前代码的修改是否适用?
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2015-04-20
    • 2021-12-22
    • 2014-04-28
    相关资源
    最近更新 更多