Menu
Topics Index
...
`

Average Scanner Demo - Java Example Program


Average Scanner Demo
import java.util.*;
import java.io.*;

class AverageScannerDemo
{
    public static void main(String arg[])
    {
        try
        {
            File
            FileWriter fout = new FileWriter("student-marks.txt");
            fout.write("25 34 21 45 27 18 49 43");
            fout.close();
        
            FileReader reader = new FileReader("student-marks.txt");
            Scanner scanner = new Scanner(reader);
        
            double sum = 0.0;
            int count = 0;
        
            while(scanner.hasNextInt())
            {
                sum += scanner.nextInt();
                count++;
            }
        
            System.out.println("Sum : " + sum);
            System.out.println("Tokens Count : " + count);
            System.out.println("Average : " + (sum/count));
        }
        catch(Exception e)
        {
            System.out.println("Exception occured : " + e.getMessage());
        }    
    }
}
OUTPUT

Sum : 262.0
Tokens Count : 8
Average : 32.75

DESCRIPTION

We prepared the sample file by writing the marks into the student-marks.txt file. After that we created a Scanner using the FileReader for the student-marks.txt. We are only looking for integers in the file using hasNextInt and reading them using nextInt method. We are summing up those integer tokens and finding the average.

THINGS TO TRY
  • Change the input to add additional tokens like Alan, true, 34.5, A in between those integer tokens and see that they are ignored, since we are only looking for integers.
  • After adding additional invalid tokens, change the methods hasNextInt/nextInt to hasNext/next and see what exception does it throw.

© meritcampus 2019

All Rights Reserved.

Open In App