Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Complete the following java program which scans a file containing only numbers a

ID: 3864549 • Letter: C

Question

Complete the following java program which scans a file containing only numbers and white space, and prints out the average value of all the numbers in the file. For instance, given a file called test containing the numbers: 2.4 3.4 5.8 6.0 7 -3 12.2 8, and given that your program is called by doing % java Problem7 test at the command line, your program will produce the following output.

Output: The average value in file test is 5.225

Your program will check that the number of command line arguments is equal to 1, and will initialize a Scanner object (in an appropriate try-catch block) pointing to the file named on the command line. If any of these tests fail, your program will exit with an error message. You may assume that the file will contain at least one number.

Outline :

// Problem7.java

import java.util.Scanner;

import java.io.*;

class Problem7{

public static void main(String[] args) throws FileNotFoundException{

// your begins here

// your code ends here

}

}

Explanation / Answer

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

class Problem7{

   public static void main(String[] args) throws FileNotFoundException{
       if(args.length < 1){
           System.out.println("Input file is not provided at coommand line ");
           return;
       }
       Scanner scanner = null;
       try{
           scanner = new Scanner(new File(args[0]));
       }catch(FileNotFoundException e){
           System.out.println("File Not found");
       }
       double total = 0.0d;
       int numOfData = 0;
       while(scanner.hasNext()){
           total += scanner.nextDouble();
           numOfData++;
       }
       double avg = total/numOfData;
       System.out.println("Avarage = "+avg);
       scanner.close();
    }

}