Question

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

Task #4 Calculating the Mean

  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. 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:
    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. 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:
    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;

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

   }

}

Homework Answers

Answer #1

CODE:

StatsDemo.java

import java.io.*;
import java.text.DecimalFormat;
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) 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();

                // ADD LINES FOR TASK #4 HERE

                FileReader file = new FileReader(filename); // Create a FileReader object passing it the filename
                BufferedReader in = new BufferedReader(file); // Create a BufferedReader object passing FileReader
                line = in.readLine(); // Perform a priming read to read the first line of the file
                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
                        line = in.readLine(); // Read a new line from the file
                }
                in.close(); // Close the input file
                mean = sum / count; // Store the calculated mean

                // ADD LINES FOR TASK #5 HERE

                file = new FileReader(filename); // Reconnect FileReader object passing it the filename
                in = new BufferedReader(file); // Reconnect BufferedReader object passing FileReader object
                sum = 0; // Reinitialize the sum of the numbers
                count = 0; // Reinitialize the number of numbers added
                line = in.readLine(); // Perform a priming read to read the first line of the file
                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
                        line = in.readLine(); // Read a new line from the file
                }
                in.close(); // Close the input file
                stdDev = Math.sqrt(sum / count); // Store the calculated standard deviation

                // ADD LINES FOR TASK #3 HERE

                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,

PLEASE UPVOTE THE ANSWER.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import java.io.*; //This imports input and output (io) classes that we use 3 //to read and write to files. The * is the wildcard that will 4 //make all of the io classes available if I need them 5 //It saves me from having to import each io class separately. 6 /** 7 This program reads numbers from a file, calculates the 8 mean (average)...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
create case 4 #include <stdio.h> int main(void) { int counter; int choice; FILE *fp; char item[100];...
create case 4 #include <stdio.h> int main(void) { int counter; int choice; FILE *fp; char item[100]; while(1) { printf("Welcome to my shopping list\n\n"); printf("Main Menu:\n"); printf("1. Add to list\n"); printf("2. Print List\n"); printf("3. Delete List\n"); printf("4. Remove an item from the List\n"); printf("5. Exit\n\n"); scanf("%i", &choice); switch(choice) { case 1: //add to list //get the input from the user printf("Enter item: "); scanf("%s", item); //open the file fp = fopen("list.txt","a"); //write to the file fprintf(fp, "\n%s", item); //close the file...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to the method header that will be a boolean variable: public boolean add(T newEntry, boolean sorted) The modification to the add method will makeit possible toadd new entriesto the beginning of the list, as it does now, but also to add new entries in sorted order. The sorted parameter if set to false will result in the existing functionality being executed (it will add the...
in jGRASP INVENTORY CLASS You need to create an Inventory class containing the private data fields,...
in jGRASP INVENTORY CLASS You need to create an Inventory class containing the private data fields, as well as the methods for the Inventory class (object). Be sure your Inventory class defines the private data fields, at least one constructor, accessor and mutator methods, method overloading (to handle the data coming into the Inventory class as either a String and/or int/float), as well as all of the methods (methods to calculate) to manipulate the Inventory class (object). The data fields...
Arrays, loops, functions: Lotto Element Repeated Function Write a function that that takes as parameters an...
Arrays, loops, functions: Lotto Element Repeated Function Write a function that that takes as parameters an array of ints, an int value named element, and an int value named end. Return a bool based on whether the element appears in the array starting from index 0 and up to but not including the end index. Generate Random Array Write a function that takes as parameters an array of integers and another integer for the size of the array. Create a...
I need this before the end of the day please :) In Java 10.13 Lab 10...
I need this before the end of the day please :) In Java 10.13 Lab 10 Lab 10 This program reads times of runners in a race from a file and puts them into an array. It then displays how many people ran the race, it lists all of the times, and if finds the average time and the fastest time. In BlueJ create a project called Lab10 Create a class called Main Delete what is in the class you...
Consider the C program (twoupdate) to demonstrate race condition. In this assignment, we will implement Peterson's...
Consider the C program (twoupdate) to demonstrate race condition. In this assignment, we will implement Peterson's algorithm to ensure mutual exclusion in the respective critical sections of the two processes, and thereby eliminate the race condition. In order to implement Peterson's Algorithm, the two processes should share a boolean array calledflagwith two components and an integer variable called turn, all initialized suitably. We will create and access these shared variables using UNIX system calls relating to shared memory – shmget,...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as possible: What is a checked exception, and what is an unchecked exception? What is NullPointerException? Which of the following statements (if any) will throw an exception? If no exception is thrown, what is the output? 1: System.out.println( 1 / 0 ); 2: System.out.println( 1.0 / 0 ); Point out the problem in the following code. Does the code throw any exceptions? 1: long value...
Write a Java program that Reads baseball data in from a comma delimited file. Each line...
Write a Java program that Reads baseball data in from a comma delimited file. Each line of the file contains a name followed by a list of symbols indicating the result of each at bat: 1 for single, 2 for double, 3 for triple, 4 for home run, o for out, w for walk, s for sacrifice Statistics are computed and printed for each player. EXTRA CREDIT (+10 points); compute each player's slugging percentage https://www.wikihow.com/Calculate-Slugging-Percentage Be sure to avoid a...