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

Write a complete method that will be called from main () . Your method will be p

ID: 3760946 • Letter: W

Question

Write a complete method that will be called from main () . Your method will be passed one argument, a String that represents a filename and its extension. The call from main () is provided below. The method you write shall attempt to open the file which, for coding purposes, will be in the C drive in a folder named data. Assume the file contains data values of type double. Assuming the file opens correctly, then calculate and return the mean. If for some reason the file does not open, or has no values stored in it, then return a value of 0 instead. The calling statement in main: d.Retval = fdCalcMean (''input. txt''); Use only these variables; be sure to declare them even though the name is provided: dSum, iCount, and dMean.

Explanation / Answer

Solution:

package com.chegg.nancy.solutions;

import java.io.File;
import java.util.Scanner;

public class ReadDouble {

   public static void main(String[] args) {

       double dRetval = fdCalcMean("input.txt");
       System.out.println("Mean = " + dRetval);

   }

   // Function to calculate mean of double values in file 'input.txt'
   private static double fdCalcMean(String fileName) {
       Scanner scan = null;
       double dSum = 0;
       int iCount = 0;
       double dMean = 0;
       File file = new File("C:\Data\" + fileName);
       try {
           scan = new Scanner(file);

           while (scan.hasNextDouble()) {
               dSum = dSum + scan.nextDouble();
               iCount++;
           }
           if (iCount != 0 && dSum != 0)
               dMean = dSum / iCount;
           else
               return 0;

       } catch (Exception e1) {
           return 0;
       } finally {
           /*
           * To close sccaner, use close() method.
           */
           if (scan != null)
               scan.close();
       }
       return dMean;
   }
}

output:

Mean = 0.0

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote