Gabriela Rosas Gabriela Rosas - 10 months ago 42
Java Question

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 Source)
at java.util.Scanner.nextDouble(Unknown Source)
at FileRead.GetAvg(
at FileRead.main(

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.*;
public class FileRead {

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

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

public static void ReadFile(Scanner reader) {

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

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

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);


Answer Source
  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.