In: Computer Science
This is a java assignment Write the body of the fileAverage() method. Have it open the file specified by the parameter, read in all of the floating point numbers in the file and return their average (rounded to 1 decimal place). For the testing system to work, don't change the class name nor the method name. Furthermore, you cannot add "throws IOException" to the fileAverage() header. Additionally, the file will have different contents during testing.
public class Main { public double fileAverage( String filename ){ } public static void main( String[] args ){ Main obj = new Main(); System.out.println( obj.fileAverage( "numbers.txt") ); } }
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public double fileAverage(String filename) {
double avg = 0;
Scanner sc = null;
try {
//opening the
file with given name
sc = new
Scanner(new File(filename));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
double sum = 0, count = 0;
//reading numbers from file
while (sc.hasNext()) {
//adding to
sum
sum +=
sc.nextDouble();
//increasing the
count
count++;
}
//finding the average
avg = sum / count;
return avg;
}
public static void main(String[] args) {
Main obj = new Main();
System.out.println(obj.fileAverage("numbers.txt"));
}
}
Note : If you like my answer please rate and help me it is very Imp for me