Scanner to read double numbers from a file and display their average.

It uses scanner to read double numbers from a file and display their average. It is assumed that input is terminated by the string “done”.


import java.util.*;

import java.io.*;

class AvgFile{

public static void main(String  a[]) throws IOException{

int count =0;

double sum=0;

//Write output to a file.

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

//Read and sum numbers

while(src.hasNext()) {

if(src.hasNextDouble()) {

sum+= src.nextDouble();

count++;

}

else {

String str =src.next();

if(str.equals("done")) break;

else {

System.out.println("ERROR");

return;

}

}

}

fin.close();

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

}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s