juicecup
juicecup

Reputation: 1

How do I read content from a .txt file and then find the average of said content in Java?

I was tasked with reading a data.txt file using the scanner import. The data.txt file looks like this:

1 2 3 4 5 6 7 8 9 Q

I need to read and find the average of these numbers, but stop when I get to something that is not an integer.

This is the code that I have so far.

public static double fileAverage(String filename) throws FileNotFoundException {
    Scanner input = new Scanner(System.in);
    String i = input.nextLine();
    while (i.hasNext);
    return fileAverage(i); // dummy return value. You must return the average here.
} // end of method fileAverage

As you can see I did not get very far and I cannot figure this out. Thank you for your help.

Upvotes: -2

Views: 68

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

First, your Scanner should be over the file filename (not System.in). Second, you should be using Scanner.hasNextInt() and Scanner.nextInt() (not Scanner.hasNext() and Scanner.nextLine()). Finally, you should add each int you read to a running total and keep track of the count of numbers read. And, I would use a try-with-resources statement to ensure the Scanner is closed. Something like,

public static double fileAverage(String filename) throws FileNotFoundException {
    try (Scanner input = new Scanner(new File(filename))) {
        int total = 0, count = 0;
        while (input.hasNextInt()) {
            total += input.nextInt();
            count++;
        }
        if (count < 1) {
            return 0;
        }
        return total / (double) count;
    }
}

Upvotes: 1

Related Questions