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

Lab Objectives • Be able to use file streams for I/O • Be able to write a loop t

ID: 3673797 • Letter: L

Question

Lab Objectives

• Be able to use file streams for I/O

• Be able to write a loop that reads until the end of a file

• Be able to implement an accumulator and a counter

Introduction

This is a simulation of rolling dice. Actual results approach theory only when the sample size is large. So we will need to repeat rolling the dice a large number of times (we will use 10,000). The theoretical probability of rolling doubles of a specific number is 1 out of 36 or approximately 278 out of 10,000 times that you roll the pair of dice. Since this is a simulation, the numbers will vary a little each time you run it. Check out how to use the random number generator (introduced in Section 4.11 of the text) to get a number between 1 and 6 to create the simulation. We will continue to use control structures that we have already learned, while exploring control structures used for repetition. We shall also continue our work with algorithms, by translating a given algorithm into java code, in order to complete our program. We will start with a while loop, then use the same program, changing the while loop to a dowhile loop, and then a for loop. We will be introduced to file input and output. We will read a file, line by line, converting each line into a number. We will then use the numbers to calculate the mean and standard deviation. First we will learn how to use file output to get results printed to a file. Next we will use file input to read the numbers from a file and calculate the mean. Finally, we will see that when the file is closed, and then reopened, we will start reading from the top of the file again so that we can calculate the standard deviation.

Task #1 Writing Output to a File

1. Copy the files StatsDemo.java (see Code Listing 4.2) and Numbers.txt from the Student CD or as directed by your instructor.

2. First we will write output to a file:

a. Create a FileWriter object passing it the filename Results.txt (Don’t forget the needed import statement).

b. Create a PrintWriter object passing it the FileWriter object.

c. Since you are using a FileWriter object, add a throws clause to the main method header.

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

e. Close the output file.

3. Compile, debug, and run. You will need to type in the filename Numbers.txt. 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 #2 Calculating the Mean

1. Now we need to add lines to allow us to read from the input file and calculate the mean.

a. Create a FileReader object passing it the filename.

b. Create a BufferedReader object passing it the FileReader object.

2. Write a priming read to read the first line of the file.

3. Write a loop that continues until you are at the end of the file.

4. The body of the loop will:

a. convert the line into a double value and add the value to the accumulator

b. increment the counter

c. read a new line from the file

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

6. Calculate and store the mean. The mean is calculated by dividing the accumulator by the counter.

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

Task #3 Calculating the Standard Deviation

1. We need to reconnect to the file so we can start reading from the top again.

a. Create a FileReader object passing it the filename.

b. Create a BufferedReader object passing it the FileReader object.

2. Reinitialize the sum and count to 0.

3. Write a priming read to read the first line of the file.

4. Write a loop that continues until you are at the end of the file.

5. The body of the loop will:

a. convert the line into a double value and subtract the mean, store the result in difference

b. add the square of the difference to the accumulator

c. increment the counter

d. read a newline from the file.

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

7. 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 the Math.sqrt method to take the square root).

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

Code Listing 4.2 (StatsDemo.java)

import java.util.Scanner;

// TASK #3 Add the file I/O import statement here

/** This class reads numbers from a file, calculates the

mean and standard deviation, and writes the results to

a file.

*/ public class StatsDemo

{ // TASK #3 Add the throws clause

public static void main(String[] args)

{ double sum = 0; // The sum of the numbers

int count = 0; // The number of numbers added

double mean = 0; // The average of the numbers

double stdDev = 0; // The standard deviation String

line; // To hold a line from the file double

difference; // The value and mean difference //

Create an object of type Scanner

Scanner keyboard = new Scanner (System.in);

String filename; // The user input file name

// Prompt the user and read in the file name

System.out.println("This program calculates " +

"statistics on a file " +

"containing a series of numbers");

System.out.print("Enter the file name: "); filename

= keyboard.nextLine();

// ADD LINES FOR TASK #4 HERE

// Create a FileReader object passing it the filename

// Create a BufferedReader object passing FileReader

// object // Perform a priming read to read the first line of

// the file // Loop until you are at the end of the file

// Convert the line to a double value and add the

// value to sum

// Increment the counter

// Read a new line from the file

// Close the input file

// Store the calculated mean //

ADD LINES FOR TASK #5 HERE

// Reconnect FileReader object passing it the

// filename //

Reconnect BufferedReader object passing

// FileReader object

// Reinitialize the sum of the numbers

// Reinitialize the number of numbers added

// Perform a priming read to read the first line of

// the file // Loop until you are at the end of the file

// Convert the line into a double value and

// subtract the mean

// Add the square of the difference to the sum

// Increment the counter

// Read a new line from the file

// Close the input file

// Store the calculated standard deviation

// ADD LINES FOR TASK #3 HERE //

Create a FileWriter object using "Results.txt"

// Create a PrintWriter object passing the

// FileWriter object

// Print the results to the output file

// Close the output file } }

Number Listings:

Explanation / Answer

import java.text.DecimalFormat;   //for number formatting
import java.util.Scanner;       //for keyboard input
import java.io.*; //ADD AN IMPORT STATEMENT HERE //for using files

public class StatsDemo
{
   public static void main(String [] args) throws IOException//ADD A THROWS CLAUSE HERE
   {
       double sum = 0;       //the sum of the numbers
       int count = 0;           //the number of numbers added
       double mean = 0;     //the average of the numbers
       double stdDev = 0;   //the standard deviation of the numbers
       String line;           //a line from the file
       double difference;   //difference between the value and the mean

       //create an object of type Decimal Format
       DecimalFormat threeDecimals = new DecimalFormat("0.000");
       //create an object of type Scanner
       Scanner keyboard = new Scanner (System.in);
       String filename;   // the user input file name

       //Prompt the user and read in the file name
       System.out.println("This program calculates statistics"
           + "on a file containing a series of numbers");
       System.out.print("Enter the file name: ");
       filename = keyboard.nextLine();

       //ADD LINES FOR TASK #2 HERE
      //Create a File object passing it the variable filename
      File ip = new File(filename);
          
       //Create a Scanner object passing it the File object
       Scanner ipFile = new Scanner(ip);
              
       //create a loop that continues until you are at the end of the file
       while (ipFile.hasNextDouble() ) {  
         //Following activities are done inside the loop
         //read the next number and add the value to the sum
           double ipDouble = ipFile.nextDouble();
         sum = sum + ipDouble;
           //increment the counter
           count++;
       }  
       //Following activities are done after the end of the loop
       //close the input file
      ipFile.close();
    
       //Calculate the mean
      mean = sum / count;

       //ADD LINES FOR TASK #3 HERE
       //reconnect to the Scanner object passing it the File object
      Scanner ip_stdDev = new Scanner (ip);
      
       //reinitialize the sum 0
      sum = 0;
       //reinitialize the counter to 0
       count = 0;      
      
       //loop that continues until you are at the end of the file
      while (ip_stdDev.hasNextDouble() ) {
         //Following activities are done inside the loop
           //read the number and subtract the mean
         double ipDouble = ip_stdDev.nextDouble();
           difference = ipDouble - mean;
           //add the square of the difference to the sum
           sum = sum + Math.pow(difference, 2);
           //increment the counter
         count ++;
       }  
       //Following activities are done after the end of the loop
       //close the input file
      ipFile.close();
       //store the calculated standard deviation
      stdDev = Math.sqrt(sum / count);

       //ADD LINES FOR TASK #1 HERE
       //create an object of type FileWriter using "Results.txt" as file name.
      FileWriter fw = new FileWriter ("Results.txt");
    
      //create an object of PrintWriter passing it the FileWriter object.
      PrintWriter pw = new PrintWriter (fw);
    
       //print the results to the output file
      pw.println("Mean: " + threeDecimals.format(mean) );
      pw.println("Standard Deviation: " + threeDecimals.format(stdDev) );
    
       //close the output file
      pw.flush();
      pw.close();
   }
}

Numbers.txt
87.5517
72.14015
88.24248
60.524
65.38684
94.48039
84.73287
84.74978
73.78996
73.43895
88.87511
102.14769
69.58979
67.28837
86.2944
82.68129


sample output

This program calculates statisticson a file containing a series of numbers                                                                                  
Enter the file name: Numbers.txt