This is a java assignment on repl.it my code works but I keep failing the tests. Can anyone help me
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.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public double fileAverage( String filename ){
Scanner sc = null;
try{
sc = new Scanner( new File(filename));
}catch(IOException e){
e.printStackTrace();
}
float f;
double sum = 0;
int count = 0;
while(sc.hasNext()){
f = sc.nextFloat();
sum += f;
count += 1;
}
return Math.round(sum/count);
}
public static void main( String[] args ){
Main obj = new Main();
System.out.println( obj.fileAverage( "numbers.txt") );
}
}
import java.io.File; import java.io.IOException; import java.util.Scanner; public class Main { public double fileAverage(String filename) { Scanner sc; try { sc = new Scanner(new File(filename)); } catch (IOException e) { return 0.0; } double sum = 0; int count = 0; while (sc.hasNext()) { sum += sc.nextDouble(); count += 1; } return Math.round(sum * 10 / count) / 10.0; } public static void main(String[] args) { Main obj = new Main(); System.out.println(obj.fileAverage("numbers.txt")); } }
Get Answers For Free
Most questions answered within 1 hours.