jeudi 5 novembre 2015

Java - Reading in salaries and getting total

So basically I'm reading in some salaries from a text file and then printing them out with a "while" loop, and then I'm adding them together with another "while" loop.

My problem is that when running the code, I get the salaries read out into the console, but I don't the total salary from the second "while" loop.

The code looks like this -

package Week15;
import java.util.*;
import java.io.*;

public class h {
    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(new File("salaries.txt"));
        double items = 0;
        double total = 0;
        double salaries;

        while (scan.hasNext()){
            salaries = scan.nextDouble();
            System.out.println(salaries);
        }   

        while (scan.hasNextDouble()) {
            // add the next salary to the total
            total += scan.nextDouble();
            // increase the number of encountered salaries by 1
            items++;
        }
        double salary = total+items;
        System.out.println("Total salary = " + salary);

        scan.close();
    }
}

The console looks like this -

14390.75
12345.99
27512.08

Here is the what the "salaries.txt" file I'm using looks like -

14390.75
12345.99
27512.08

Aucun commentaire:

Enregistrer un commentaire