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)...
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...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the following subsections can all go in one big file called pointerpractice.cpp. 1.1     Basics Write a function, int square 1(int∗ p), that takes a pointer to an int and returns the square of the int that it points to. Write a function, void square 2(int∗ p), that takes a pointer to an int and replaces that int (the one pointed to by p) with its...
this is the book name. Data Structures and Abstractions with Java 1) Description: The sample programs...
this is the book name. Data Structures and Abstractions with Java 1) Description: The sample programs in Chapter 1 of your textbook are not complete. They are used for illustration purpose only. The implementation of Listing 1-1 on page 39 is explained in Chapter 2. And, in order to see the result of using it, we will need the following set of files: i. BagInteface.java – the specification only. ii. ArrayBag.java – the implementation of BagInerface.java. iii. ArrayBagDemo.java – a...
Can someone please edit my code so that it satisfies the assignments' requirements? I pasted the...
Can someone please edit my code so that it satisfies the assignments' requirements? I pasted the codes below. Requirement: Goals for This Project:  Using class to model Abstract Data Type  OOP-Data Encapsulation You are asked to write an app to keep track of a relatively small music library. The app should load song information from a data file once the app is started. It should allow user to view, add, remove, and search for songs. The app should...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code to initialize the CustomerAccountsDB database table and add a set of customer accounts is provided. Finish the code in these 3 methods in CustomerAccountDB.java to update or query the database: -purchase(double amountOfPurchase) -payment(double amountOfPayment) -getCustomerName() Hint: For getCustomerName(), look at the getAccountBalance() method to see an example of querying data from the database. For the purchase() and payment() methods, look at the addCustomerAccount() method...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop a class, using templates, to provide functionality for a set of recursive functions. The functions specified as recursive must be written recursively (not iterativly). The UML class specifications are provided below. A main will be provided. Additionally, a make file will need to be developed and submitted. ● Recursion Set Class The recursion set template class will implement the template functions. recursionSet -length: int...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT