Question

# Task #4 Calculating the Mean Now we need to add lines to allow us to read...

1. Now we need to add lines to allow us to read from the input file and calculate the mean.
1. Create a FileReader object passing it the filename.
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:
1. convert the line into a double value and add the value to the accumulator
2. increment the counter
3. 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 #5 Calculating the Standard Deviation

1. We need to reconnect to the file so we can start reading from the top again.
1. Create a FileReader object passing it the filename.
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:
1. convert the line into a double value and subtract the mean, store the result in difference
2. add the square of the difference to the accumulator
3. increment the counter
4. 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.1 (DiceSimulation.java)

import java.util.Random;   // Needed for the Random class

/**

This class simulates rolling a pair of dice 10,000 times    and counts the number of times doubles of are rolled for    each different pair of doubles.

*/

public class DiceSimulation

{

public static void main(String[] args)

{

final int NUMBER = 10000; // Number of dice rolls

// A random number generator used in

// simulating the rolling of dice

Random generator = new Random();

int die1Value;       // Value of the first die       int die2Value;       // Value of the second die       int count = 0;       // Total number of dice rolls       int snakeEyes = 0;   // Number of snake eyes rolls       int twos = 0;        // Number of double two rolls       int threes = 0;      // Number of double three rolls       int fours = 0;       // Number of double four rolls       int fives = 0;       // Number of double five rolls       int sixes = 0;       // Number of double six rolls

// TASK #1 Enter your code for the algorithm here        // Display the results

System.out.println ("You rolled snake eyes " +                           snakeEyes + " out of " +                           count + " rolls.");       System.out.println ("You rolled double twos " +                           twos + " out of " + count +

" rolls.");

System.out.println ("You rolled double threes " +                           threes + " out of " + count +

" rolls.");

System.out.println ("You rolled double fours " +                           fours + " out of " + count +                           " rolls.");

System.out.println ("You rolled double fives " +                           fives + " out of " + count +                           " rolls.");

System.out.println ("You rolled double sixes " +                           sixes + " out of " + count +

" rolls.");

}

}

Code Listing 4.2 (StatsDemo.java)

import java.util.Scanner;

/**

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();

// object

// 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

// Reconnect FileReader object passing it the

// filename

// Reinitialize the sum of the numbers

// Reinitialize the number of numbers added

// 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

// 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

}

}

CODE:

StatsDemo.java

``````import java.io.*;
import java.text.DecimalFormat;
import java.util.Scanner;

/**
*
* This class reads numbers from a file, calculates the mean and standard
* deviation, and writes the results to a file.
*
*/

public class StatsDemo {

public static void main(String[] args) throws IOException {
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
DecimalFormat f = new DecimalFormat("##.000"); // To format decimal value to 3 places
Scanner keyboard = new Scanner(System.in); // Create an object of type Scanner
String filename; // The user input 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(); // Prompt the user and read in the file name
keyboard.close();

while (null != line) { // Loop until you are at the end of the file
sum += Double.parseDouble(line); // Convert the line to a double value and add the value to sum
count++; // Increment the counter
}
in.close(); // Close the input file
mean = sum / count; // Store the calculated mean

file = new FileReader(filename); // Reconnect FileReader object passing it the filename
sum = 0; // Reinitialize the sum of the numbers
count = 0; // Reinitialize the number of numbers added
while (null != line) { // Loop until you are at the end of the file
difference = Double.parseDouble(line) - mean; // Convert the line to a double value and subtract the mean
sum += Math.pow(difference, 2); // Add the square of the difference to the sum
count++; // Increment the counter
}
in.close(); // Close the input file
stdDev = Math.sqrt(sum / count); // Store the calculated standard deviation

FileWriter fileOut = new FileWriter("Results.txt");// Create a FileWriter object using "Results.txt"
PrintWriter result = new PrintWriter(fileOut);// Create a PrintWriter object passing the FileWriter object
result.print(f.format(mean) + "\n" + f.format(stdDev)); // Print the results to the output file
result.close();
file.close(); // Close the output file
System.out.println("Successful"); // To show the operation was successful
}

}``````

Please be careful while writing the filename. It should be full file name. For eg - sample.txt

Also if you are entering only the filename without the path then the file should be in the same project ( and not the same package ) as the StatsDemo.java class. The file Results.txt will also be generated in the same project folder.

THANKS,

#### Earn Coins

Coins can be redeemed for fabulous gifts.