Trying to read from a file to work out an average - java

I am currently reworking tasks that were set at the beginning of the year and one thing I didn't really understand the concepts on: loops and read / write to / from files. The challenge is to read a bunch of salaries from a text file, add them and calculate the average, and then print the results to the console.

So far I have this:

import java.util.*;
import java.io.*;

public class loopingSalaryTotal {
    public static void main (String[] args) throws IOException {
        int [] salaries = new int[100];
        Scanner scan = new Scanner("salaries1.txt");
        int index = 0;

        while (scan.hasNext()) {
            salaries[index]=(scan.nextInt());
            index++;
        }

        for (int i = 0; i < index; i++) {
            System.out.println(salaries[i]);
        }

        scan.close();
    }
}

      

And it is throwing this error message:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at loopingSalaryTotal.main(loopingSalaryTotal.java:18)

      

Also, I fully understand that I cannot actually compose the numbers anywhere and then calculate the average, but if someone can nudge me in the right direction that would be very helpful.

Here's an example of input from input.txt

:

17283
12312
12312
12314
43242
64363
12364
74534

      

+3


source to share


4 answers


If you only want the average, you don't need to store every salary. Instead, store the running sum before calculating the average at the end:

import java.util.*;
import java.io.*;

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

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

        scan.close();
    }
}

      

Your problem is also what you should be using Scanner.hasNextInt

. This is because it Scanner.hasNext

might return true

even though there are more integers in your file. For example, if your file was



125
172
199
zalgo_calls_your_name

      

After reaching 199, Scanner.hasNext

will return true. However, there is no integer string after the 199th integer. So when you call Scanner.nextInt

in your loop, an exception is thrown as int cannot be found.

+1


source


Your input file probably contains spaces that the scanner is wrong about. You must add a try catch block to your while loop:



while (scan.hasNext()){
    try{
        salaries[index]=(scan.nextInt());
    } catch(InputMismatchException e){
        salaries[index]=-1; //Or some kind of identifier that something went wrong
    }
    index++;
}

      

0


source


There may be empty space. Read the string as String, trim it and then parse it with Int.

0


source


You're doing it all wrong ...

Scan Scanner = New Scanner ("salaries1.txt");

A new scanner is created above the constructor that produces the values ​​scanned from the specified string and you are reading from a file, not a string.

What you have to do is

File file = new file ("salaries1.txt");

Scan scan = new scanner (file);

0


source







All Articles