简体   繁体   中英

Calculating average of numbers from a file in Java?

I'm working on a program that is supposed to read numbers from a file and not only print them, but also find and report the average. However, I keep running into errors such as:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at FileRead.GetAvg(FileRead.java:36)
    at FileRead.main(FileRead.java:18)

I'm a beginner and not sure what exactly is going wrong. If someone could let me know exactly what my errors are or steer me in the right direction if I'm completely wrong, it would be appreciated. I've been working at this for days and keep running into errors. Here is my code:

import java.util.*;
import java.io.*;
public class FileRead {

    public static void main(String[] args) throws FileNotFoundException {


        Scanner input = new Scanner(System.in);
        System.out.println("Input filename (Be sure to add .txt):");
        String filename = input.nextLine();
        File inputFile = new File(filename);
        Scanner reader = new Scanner(inputFile);
        ReadFile(reader);
        GetAvg(reader);
    }

    public static void ReadFile(Scanner reader) {           

        System.out.println("The numbers are: ");

        double count = reader.nextDouble();
        System.out.println(count);
        while (reader.hasNextDouble()){
            for (int i=0; i<count; i++);{
                System.out.println(reader.nextDouble());

            }
        }
    } 
    public static void GetAvg(Scanner reader) {           
        double count = 8;
        double numbers = reader.nextDouble();

        double sum = 0;

        for(int i=0; i <=count ; i++)
            sum = sum + numbers;

        double average = sum / count;

        System.out.println("Average is : " + average);



    }
}
  1. reader is at the end of the file before GetAvg starts, because ReadFile found the end of it.

reader is an object that was initialized in main , passed by-reference to ReadFile , as well as to GetAvg . Passed-by-reference means that any changes that ReadFile made to its state will be true in the scope of main and anything else, after ReadFile is done.

when main called ReadFile(reader); , ReadFile worked its' way through the file until it found the end of it.

            while (reader.hasNextDouble()){

This returns false when the reader has no more data in the file to process, allowing the loop to terminate and with it, the readFile method.

After ReadFile is done, main passes the same reader object into GetAvg . There is no nextDouble for GetAvg to get, because it already reached the end of the file during ReadFile

  1. The for loop is not necessary, and is skipping numbers.

Let's say the first number in the file was 4.7 The for loop would then pull and print the next four numbers. It will not print the 4.7

Without the for loop, this line of code will print the 4.7. The loop would then continue again with the next double it found in the file.

    System.out.println(reader.nextDouble());

The problem is you are passing the same scanner to both ReadFile() and GetAvg(). Take a look at this . You have already exhausted the scanner by the time you reach GetAvg() and, therefore, double numbers = reader.nextDouble(); throws an error because the next double in the file is nonexistent.

A quick fix might be this:

File inputFile = new File(filename);
Scanner reader = new Scanner(inputFile);
ReadFile(reader);
Scanner reader = new Scanner(inputFile);
GetAvg(reader);  

Couple flaws in the function ReadFile:

  • double count = reader.nextDouble(); this wouldn't give you the count of the floats in the string/text
  • You got NoSuchElementException because the input is exhausted, there is no more double.
  • You can use hasNext() as follows (which you are already using but I don't think for loop is necessary for what you are trying to achieve and no use of determining the count first. eg - Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); }
  • You can determine the count by adding a counter in the while loop which adds 1 to itself if a double is found ( count++ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM