gpt4 book ai didi

java - 在循环中将所有 double 相加,Java

转载 作者:行者123 更新时间:2023-12-02 12:04:54 29 4
gpt4 key购买 nike

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

我目前拥有的代码如下:

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);

}
}

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

最佳答案

我会这样做。看来您正在尝试迭代两次而不重置迭代器。

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();

}
}

关于java - 在循环中将所有 double 相加,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46961950/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com