在循环中添加所有双精度数,Java

时间:2017-10-26 19:03:57

标签: java

所以我必须创建这个程序,从文件中读取一些“工资”,然后将所有工资加起来以返回一个“总工资”,并计算所有工资的平均值。

我目前的代码如下:

package uploadTask7_countingSalaries;

//import utilities needed for the program
import java.util.Scanner;
import java.io.File;

public class countingSalaries {

    public static void main(String[] args) throws Exception { 
        // defines the file that data will be read from
        File salaryFile = new File("salaries.txt");
        // creates scanner object to read data from file
        Scanner scanFile = new Scanner (salaryFile);
        // creates while loop to read and print data to the user
        while(scanFile.hasNextDouble()) {
            double i = scanFile.nextDouble();
            System.out.println(i); }

        double addedSalary = scanFile.nextDouble();
        double sumofSalary = 0.0;
        while(scanFile.hasNextDouble()) {
            sumofSalary += addedSalary;
            addedSalary++; }

        System.out.println("Total salary is: " + addedSalary);

        }
    }

到目前为止,我已经能够从文本文件中读取工资并将其打印出来给用户。我正在努力找到一种方法来添加所有数字/使用循环计算外部文件的平均值。

3 个答案:

答案 0 :(得分:1)

我会这样做。看来你试图迭代两次而不重置迭代器。

package uploadTask7_countingSalaries;

//import utilities needed for the program
import java.util.Scanner;
import java.io.File;

public class countingSalaries {

    public static void main(String[] args) throws Exception { 
        List<Double> salaries = new ArrayList<Double>();
        // defines the file that data will be read from
        File salaryFile = new File("salaries.txt");
        // creates scanner object to read data from file
        Scanner scanFile = new Scanner (salaryFile);
        // creates while loop to read and print data to the user
        while(scanFile.hasNextDouble()) {
            double i = scanFile.nextDouble();
            salaries.add(i);
            System.out.println(i); }

       double total = 0;
       for(double a : salaries){
        total = total + a;
       }

        System.out.println("Total salary is: " + total);
        System.out.println("Avg = " + total/salaries.size();

        }
    }

答案 1 :(得分:0)

你必须在你的while循环中阅读每一个之后总结工资,所以在每次阅读之后你会得到一个部分金额。获得总和后,您可以根据总和和您已阅读的元素数计算平均值。

答案 2 :(得分:0)

试试这个:

您需要一个额外的int变量,它保存读取的工资数量,然后您可以使用此变量来计算平均值。

double addedSalary = scanFile.nextDouble();
            double sumofSalary = 0.0;
            int count = 0;
            while(scanFile.hasNextDouble()) {
                count ++;
                sumofSalary += addedSalary;
                addedSalary++; }
            double average = sumofSalary/ count;

            System.out.println("Total salary is: " + addedSalary);