myles438a
myles438a

Reputation: 31

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

Upvotes: 1

Views: 745

Answers (4)

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

You have reached the end of file, when you exit first loop. You should again initialize

scan = new Scanner(new File("salaries.txt")); 

after first loop. Your code will work.

Upvotes: 0

rns
rns

Reputation: 1091

There is no need of second while loop.

    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);
        total += salaries;
    }

    double salary = total + items;
    System.out.println("Total salary = " + salary);

    scan.close();

In the first loop itself the scanner has completed all its token(element).

Upvotes: 0

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22224

You should merge the 2 loops :

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

    // add the next salary to the total
    total += salaries;
    // increase the number of encountered salaries by 1
    items++;
}

Otherwise the first loop finishes scanning the file and you never get in the second loop as scan.hasNextDouble() returns false

Upvotes: 1

Stefan
Stefan

Reputation: 1433

while (scan.hasNextDouble()) {

This does not return true because the end of the file was reached. Try to sum your total in the first while loop:

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

You can also add your items count there.

Upvotes: 1

Related Questions