Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

loops

I'm currently re-working through tasks that I was set at the start of the year and one thing I really didn't grasp the concepts of was loops and reading/writing to/from files. The task in hand is to read in a bunch of salaries from a text file, add them up and calculate an average and then print out the results in 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's 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'm nowhere near being able to actually add up the numbers then calculate an average, but if anyone could nudge me in the right direction that'd be greatly appreciated.

Here is some example input from input.txt:

17283
12312
12312
12314
43242
64363
12364
74534
like image 357
Brody Avatar asked Nov 17 '25 00:11

Brody


1 Answers

If you only want the average, then you don't need to store each salary. Instead, keep a running total 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 that you should use Scanner.hasNextInt. This is because Scanner.hasNext may return true even though there are no more integers in your file. For example, if your file were

125
172
199
zalgo_calls_your_name

After reaching 199, Scanner.hasNext would return true. However, there is no integer after 199—just a string. So, when you call Scanner.nextInt in your loop, an exception is thrown since no int can be found.

like image 86
royhowie Avatar answered Nov 19 '25 14:11

royhowie