Use Scanner to compute an average a list of comma-separated values : Scanner « Development Class « Java






Use Scanner to compute an average a list of comma-separated values

 
/**
 *Output:
 Average is 6.2
 */

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class MainClass {
  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);

    src.useDelimiter(", *");

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

           
         
  








Related examples in the same category

1.Read int by using Scanner Class
2.Use Scanner to read user input
3.Count all vowels inputed from keyboard
4.Use Scanner to compute an average of the values
5.Use Scanner to compute an average of the values in a file
6.Use Scanner to read various types of data from a file
7.Demonstrate findInLine()
8.use Scanner to read input that contains several different types of data
9.Letting the user decide when to quit
10.Test the input string in the while condition.
11.This program demonstrates console input.
12.Reading double value from console with ScannerReading double value from console with Scanner