Reputation: 37
So I have to create this program that reads a number of 'salaries' from a file, then adds all the salaries up to return one 'total salary' and also calculates the average of all the salaries.
The code I currently have is below:
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);
}
}
So far I've been able to read the salaries from the text file and print them out to the user. I'm struggling to find a way to add up all the numbers / calculate the average from the external file using a loop.
Upvotes: 0
Views: 2401
Reputation: 1394
I would do it this way. It seems you are trying to iterate twice without resetting the iterator.
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();
}
}
Upvotes: 1
Reputation: 347
Try this:
You need an additional int variable, that holds the number of salaries read , and then you can use this variable to calculate the average.
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);
Upvotes: 0
Reputation: 186
You have to sum up the salaries after reading each of them in your while loop so after each read you'll have a partial sum. After you get the sum, you can calculate the average based on the total sum and the count of elements you've read.
Upvotes: 0