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

Task #3 Reading and Writing Using Files 1. Refer to Lab 5 in lab, FileStats.java

ID: 3681527 • Letter: T

Question

Task #3 Reading and Writing Using Files

1. Refer to Lab 5 in lab, FileStats.java below, you can compile FileStats.java. It will compile without errors so that you can use it to test out the StatsDemo class you will be creating.

2. Create a class called StatsDemo which consists of a main method to do the following:

a) Create a DecimalFormat object so that we can format our numbers for output with 3 decimal places (Don’t forget the needed import statement).

b) Create a Scanner object to get the file name input from the user (Don’t forget the needed import statement).

c) Prompt the user and read in the file name (Remember to declare any needed variables).

d) Create a FileStats object passing it the file name.

e) Create a PrintWriter object passing it the filename “Results.txt” (Don’t forget the needed import statement).

f) Since you are using a PrintWriter object, add a throws clause to the main method header.

g) Print the mean and standard deviation to the output file using a three decimal format, labeling each.

h) Close the output file.

3. Compile, debug, and run. You should get no output to the console, but running the program will create a file called Results.txt with your output. The output you should get at this point is: mean = 0.000, standard deviation = 0.000. This is not the correct mean or standard deviation for the data, but we will fix this in the next tasks.

Task #4 The calculateMean Method

1. Open FileStats.java for editing. You will notice that the calculateMean and calculateStdDev methods do not do any calculations yet. They simply return a 0 to the constructor to initialize the instance variables. We need to add lines to each of these methods to have them return the correct value. Let’s work with the calculateMean method first.

2. Create a File object passing it the filename (Don’t forget the needed import statement).

3. Create a Scanner object passing it the File object.

4. Since you are using a Scanner object to open a file, add a throws clause to the calculateMean method header as well as the constructor method header (since it calls the calculateMean method).

5. Declare local variables for an accumulator of type double, a counter of type integer, and line of type String. Initialize all number variables to 0.

6. Write a loop that reads values from the file until you are at the end of the file.

7. The body of the loop will

a) read a double from the file and add the value to the accumulator

b) increment the counter

8. When the program exits the loop close the input file.

9. Calculate and return the mean instead of 0. The mean is calculated by dividing the accumulator by the counter.

10. Compile, debug, and run. You should now get a mean of 77.444, but the standard deviation will still be 0.000.

Task #5 The calculateStdDev Method

1. Do steps 2-6 as above in the calculateMean method but add another local variable called difference of type double.

2. The body of the loop will

a) read a double value from the file, subtract the mean from that value, and

store the result in difference

b) add the square of the difference to the accumulator

c) increment the counter

3. When the program exits the loop close the input file.

4. The variance is calculated by dividing the accumulator (sum of the squares of the difference) by the counter. Calculate the standard deviation by taking the square root of the variance (Use Math.sqrt ( ) to take the square root).

5. Compile, debug, and run. You should get a mean of 77.444 and standard deviation

of 10.021.

……………………………………………………………………………………>

FileStats.java

…………………………………………………………………………………….>

// To calculate the statistics on a file of numbers

public class FileStats

{

            private double mean;   //the arithmetic average

            private double stdDev; //the standard deviation

            //Constructor calls calculateMean and calculateStdDev methods

            //and store the results in the respective instance variables

            public FileStats(String filename)

            {

                        mean = calculateMean(filename);

                        stdDev = calculateStdDev(filename);

            }

            //returns the mean

            public double getMean()

            {

                        return mean;

            }

            //returns the standard deviation

            public double getStdDev()

            {

                        return stdDev;

            }

            //returns the calculated arithmetic average

            public double calculateMean(String filename)

            {

                        //ADD LINES FOR TASK 4

                        return 0;

            }

            //returns the calculated standard deviation

            public double calculateStdDev(String filename)

            {

                        //ADD LINES FOR TASK 5

                        return 0;

            }

}

//…………………………………………………………………………………………>

Explanation / Answer

StatsDemo.java
/**
* StatsDemo class
*/
import java.util.Scanner;           //for keyboard input
import java.io.*;                       //for using files

public class StatsDemo
{
   public static void main(String [] args) throws IOException
   {
       //create an object of type Decimal Format
       //create an object of type Scanner
       Scanner keyboard = new Scanner (System.in);
       String inFilename;   // the user input file name
       String outFilename;

       inFilename = "Numbers.txt";
       outFilename = "Results.txt";

       //create an object of type Stats using the user input file name
       FileStats stats = new FileStats(inFilename);

       //create an object of PrintWriter using "Results.txt".
       PrintWriter output = new PrintWriter(outFilename);

       //print the results to the output file
       output.println("mean = " + stats.getMean());
       output.println("standard deviation = " + stats.getStdDev());

       //close the output file
       output.close();
   }
}

FileStats.java

// To calculate the statistics on a file of numbers

import java.io.*;          // for I/O classes
import java.util.Scanner; // for the Scanner class

public class FileStats
{
   private double mean; //the arithmetic average
   private double stdDev;//the standard deviation

   //Constructor calls calculateMean and calculateStdDev methods
   //and store the results in the respective instance variables
   public FileStats(String filename) throws IOException
   {
      mean = calculateMean(filename);
      stdDev = calculateStdDev(filename);
   }

   //returns the mean
   public double getMean()
   {
      return mean;
   }

   //returns the standard deviation
   public double getStdDev()
   {
      return stdDev;
   }

   //returns the calculated arithmetic average
   public double calculateMean(String filename)throws IOException
   {
      //Create a File object passing it the filename
      File file = new File(filename);
      //Create a Scanner object passing it the File object.
      Scanner input = new Scanner(file);

      double total = 0;   //the sum of the numbers
      int count = 0;     //the number of numbers added

      //loop that continues until you are at the end of the file
      while (input.hasNext())
      {
         //convert the line into a double value and add the value to the sum
         total += input.nextDouble();
         //increment the counter
         count++;
      }

      //close the input file
      input.close();

      //return the calculated mean
      return total/count;
   }

   //returns the calculated standard deviation
   public double calculateStdDev(String filename)throws IOException
   {
      //Create a File object passing it the filename
      File file = new File(filename);
      //Create a Scanner object passing it the File object.
      Scanner input = new Scanner(file);

      double total = 0;   //the sum of the numbers
      int count = 0;     //the number of numbers added
      double difference; //difference between the value and the mean

      //loop that continues until you are at the end of the file
      while (input.hasNext())
      {
         //convert the line into a double value and subtract the mean
         difference = input.nextDouble()- mean;

         //add the square of the difference to the sum
         total += Math.pow(difference,2);

         //increment the counter
         count++;
      }

      //close the input file
      input.close();

      //return the calculated mean
      return Math.sqrt(total/count);

   }
}

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