Use Scanner to read from a file compute an average of the values in Java

Description

The following code shows how to use Scanner to read from a file compute an average of the values.

Example


//  w w w  .j ava  2  s .  c om
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main {
  public static void main(String args[]) throws IOException {

    int count = 0;
    double sum = 0.0;

    FileWriter fout = new FileWriter("test.txt");
    fout.write("2 3.4 5 6 7.4 9.1 10.5 done");
    fout.close();

    FileReader fin = new FileReader("Test.txt");

    Scanner src = new Scanner(fin);

    while (src.hasNext()) {
      if (src.hasNextDouble()) {
        sum += src.nextDouble();
        count++;
      } else {
        String str = src.next();
        if (str.equals("done"))
          break;
        else {
          System.out.println("File format error.");
          return;
        }
      }
    }

    fin.close();
    System.out.println("Average is " + sum / count);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip