【问题标题】:Can I get help to calculate average and total?我可以得到帮助来计算平均值和总数吗?
【发布时间】:2016-04-13 01:39:54
【问题描述】:

我打开了一个文件,打印出来很好,看起来有点像这样;

约翰霍普 13 12.00

劳拉小屋 6 15.00

但是数组是 6。由于我有另一个带有 getter 和 setter 的类,因此该文件能够获取每个人的总工资:

约翰 13 12.00 150.00

劳拉小屋 6 15.00 120.00

我想打印所有个人的总工资,然后得到平均值。 这是我的一些代码

public class PayRoll {

public static void main(String[] args) {
    final int NUMBER_OF_WORKERS = 15;

    final String INPUT_FILE = "data.txt";
    Worker[] worker_ar = new Worker[NUMBER_OF_WORKERS];

    Scanner file = null;

    try {

        file = new Scanner(new File(INPUT_FILE));
    } catch (FileNotFoundException e) {
        System.err.println("File Not Found!");
    }

    String line = null;
    int count = 0;
    double total_pay = 0;
    double avg_pay = 0;

    while ((file.hasNextLine()) && (count < worker_ar.length)) {
        String fName = file.next();
        String lName = file.next();
        int hours = file.nextInt();
        double hrly_pay = file.nextDouble();

        worker_ar[count] = new Worker(fName, lName, hours, hrly_pay);

        count++;
//Here, i tried computing the average but it is wrong. 
        for (int i = 0; i < count; i++)
            total_pay = total_pay + worker_ar[i].computePay();

            avg_pay = total_pay / count;

【问题讨论】:

  • 您不需要在 while 循环中使用 for() 循环。把它放在while 循环运行之后,你把所有的工资加到total_pay 并除以count。编辑:就像艾略特提交的答案一样。

标签: java arrays file class methods


【解决方案1】:

在计算总数和平均值(或至少是平均值)之前完成文件内容的读取。类似的东西

double total_pay = 0;
while ((file.hasNextLine()) && (count < worker_ar.length)) {
    String fName = file.next();
    String lName = file.next();
    int hours = file.nextInt();
    double hrly_pay = file.nextDouble();
    worker_ar[count] = new Worker(fName, lName, hours, hrly_pay);
    total_pay += worker_ar[count].computePay(); // <-- add this worker's
                                                //     pay to the total.
    count++;
}
double avg_pay = total_pay / count; // <-- calculate the average when 
                                    //     there is a total.

【讨论】:

  • 非常感谢。有效。这些小细节确实会影响程序。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 2010-11-25
  • 2016-11-14
  • 2021-08-20
  • 2018-09-26
相关资源
最近更新 更多