First, launch NetBeans and close any previous projects that may be open (at the top menu go to File ==> Close All Projects).Then create a new Java application called "WeightedAvgDataAnalyzer" (without the quotation marks), that modifies the DataAnalyzer.java in Horstmann Section 7.5, pp. 350-351 according to the specifications below.The input file should be called 'data.txt' and should be created according to the highlighted instructions below. Note that even though you know the name of the input file, you should not hard-code this name into your program. Instead, prompt the user for the name of the input file.The input file should contain (in order): the weight (a number greater than zero and less than or equal to 1), the number, n, of lowest numbers to drop, and the numbers to be averaged after dropping the lowest n values.You should also prompt the user for the name of the output file, and then print your results to an output file with the name that the user specified.Your program should allow the user to re-enter the input file name if one or more of the exceptions in the catch clauses are caught.Your methods for getting data and printing results should each throw a FileNotFoundException which should be caught in the main method.Use try-with-resources statements(Links to an external site.)in your methods for getting and printing the data, and so avoid the need to explicitly close certain resources.In your readData method, use hasNextDouble to check ahead of time whether there's a double in the data. That way when you try to get the nextDouble, your code won't throw a NoSuchElementException.You can use a writeFile method that does all the work (i.e., does not call a writeData method the way that Horstmann’s readFile method calls a readData method). Use a try-with-resources statement in your writeFile method when creating a new PrintWriter.The inputValues come from a single line in a text file (data.txt) such as the following: 0.5 3 10 70 90 80 20The output in the output file must give the weighted average, the data and weight that were used to calculate the weighted average, and the number of values dropped before the weighted average was calculated.Your output should look very much like the following: "The weighted average of the numbers is 42.5, when using the data 10.0, 70.0, 90.0, 80.0, 20.0, where 0.5 is the weight used, and the average is computed after dropping the lowest 3 values."Write the output to a file with the filename that the user chose to name the output file (e.g., output.txt). Don't hard-code the output file name in your program.

Question
Asked Dec 16, 2019
12 views

First, launch NetBeans and close any previous projects that may be open (at the top menu go to File ==> Close All Projects).
Then create a new Java application called "WeightedAvgDataAnalyzer" (without the quotation marks), that modifies the DataAnalyzer.java in Horstmann Section 7.5, pp. 350-351 according to the specifications below.
The input file should be called 'data.txt' and should be created according to the highlighted instructions below. Note that even though you know the name of the input file, you should not hard-code this name into your program. Instead, prompt the user for the name of the input file.
The input file should contain (in order): the weight (a number greater than zero and less than or equal to 1), the number, n, of lowest numbers to drop, and the numbers to be averaged after dropping the lowest n values.
You should also prompt the user for the name of the output file, and then print your results to an output file with the name that the user specified.
Your program should allow the user to re-enter the input file name if one or more of the exceptions in the catch clauses are caught.
Your methods for getting data and printing results should each throw a FileNotFoundException which should be caught in the main method.
Use try-with-resources statements
(Links to an external site.)
in your methods for getting and printing the data, and so avoid the need to explicitly close certain resources.
In your readData method, use hasNextDouble to check ahead of time whether there's a double in the data. That way when you try to get the nextDouble, your code won't throw a NoSuchElementException.
You can use a writeFile method that does all the work (i.e., does not call a writeData method the way that Horstmann’s readFile method calls a readData method). Use a try-with-resources statement in your writeFile method when creating a new PrintWriter.
The inputValues come from a single line in a text file (data.txt) such as the following:
0.5 3 10 70 90 80 20
The output in the output file must give the weighted average, the data and weight that were used to calculate the weighted average, and the number of values dropped before the weighted average was calculated.
Your output should look very much like the following: "The weighted average of the numbers is 42.5, when using the data 10.0, 70.0, 90.0, 80.0, 20.0, where 0.5 is the weight used, and the average is computed after dropping the lowest 3 values."
Write the output to a file with the filename that the user chose to name the output file (e.g., output.txt). Don't hard-code the output file name in your program.

check_circle

Expert Answer

Step 1

Following is the source code according to the requirements given in the question. Comments have been added in the code for the better understanding of the source code.

Java Source Code

//import the required packages

import java.io.File;

import java.io.FileWriter;

import java.io.PrintWriter;

import java.util.Arrays;

import java.util.LinkedList;

import java.util.Scanner;

//define a class as mentioned in the question

public class WeightedAvgDataAnalyzer

{

  //create a LinkedList to store the input data

  public static LinkedList<LinkedList<Double>> inputData = new LinkedList<LinkedList<Double>>();

  //create another LinkedList to store the calculated input data

  public static LinkedList<String> outputData = new LinkedList<String>();

  public static void main(String[] args)

  {

      Scanner sc = null;// create the object of Scanner class

      try

      {

          sc = new Scanner(System.in);// allocate memory to the object of Scanner class

          //iterate infinite loop till user enters correct input file

          while (true)

          {

              System.out.println("Enter the name of input file:");

              String inputFileName = sc.next(); //get the input file name from user

              File file = new File(inputFileName); //create the File object using Input File Name

              //check whether the input file is exists or not

              if (file.exists())

              {

                  //read the data from the input file and create the data list

                  readData (inputFileName);

                  break;//end of infinite loop

              }

              else

              {

                  System.out.println("File not found!");

              }     

          }

          System.out.println("Enter the name of the output file:");

          String outputFileName = sc.next(); //get the Output File Name from the user

          Weighted_Average(); //calling of the function to calculate the average weighted value of the input data

          writeFile (outputFileName);//writing of the Average Weighted Value to the output file

      }

      catch (Exception e)

      {

          e.printStackTrace();

      }

      finally

      {

          try

          {

              if (sc!= null)

              {

                  sc.close();//close the Scanner object

              }

          }

          catch (Exception e)

          {

              e.printStackTrace();

          }

      }

  }//end of main()

  // Definition of reading file

  public static void readData(String fileName)

  {

      try (Scanner scan = new Scanner(new File(fileName)))

      {

          //iterate the scanner for each line of input text file

          while (scan.hasNextDouble())

          {

              String line = scan.nextLine();// get the new line from text file

              // Split each line by space to get the string array

              String[] lineArray = line.trim().split("s+");

              //create the sublist for each line of input text file

              LinkedList<Double> sub_DataList = new LinkedList<Double>();

              sub_DataList.add(Double.parseDouble(lineArray[0])); //add the weight in the list

              sub_DataList.add(Double.parseDouble(lineArray[1])); //add the dropping value

              //iterate the loop to get the Data from the line

              for (int i=2;i<lineArray.length;i++)

              {

                  sub_DataList.add(Double.parseDouble(lineArray[i])); //Add rest of the data

              }

              inputData.add(sub_DataList);//add the sub list in the actual list

          }

      }

      catch (Exception e)

      {

          e.printStackTrace();

      }

  }

  // Definition of the called method

  public static void Weighted_Average ()

  {

      try

      {

          //Check whether the input list is not empty

          if (inputData != null && inputData.size()>0)

          {

              //iterate the input list

              for (int i=0;i<inputData.size();i++)

              {

                  LinkedList<Double> sub_DataList = inputData.get(i);//Getting each sublist

                  //Check whether the sublist is not empty

                  if (sub_DataList != null && sub_DataList.size()>0)

                  {

                      //Write the output message

                      String output1 = "The weighted average of the numbers is ";

                      String output2 = ", when using the data ";

                      Double weight = sub_DataList.get(0);//Get the weight

                      double dropingValue = sub_DataList.get(1);//Get the dropping value

                      Double[] dataArry = new Double[sub_DataList.size()-2];//Create the array of the data

                      int dataCount = 0;//Declare the data count as zero

                      //iterate the loop to get data and add them into double array

                      for (int j=2;j<sub_DataList.size();j++)

                      {

                          output2 = output2 + sub_DataList.get(j) +", ";//create the output message as given in the question

                          dataArry[dataCount] = sub_DataList.get(j);//add the data in the array

                          dataCount++;//increase data count by 1

                      }

                      output2 = output2+" where "+weight+ " is the weight used, and the average " +

                      "is computed after dropping the lowest "+(int)dropingValue+" values.";

                      Arrays.sort(dataArry);//Sort the data array

                      double totalWeightedValue = 0;//Declare the total Weighted Value

                      dataCount = 0;//set the data count as zero again

                      // iterate loop till dropping values reached in the array

                      for (double k=(int)dataArry.length-1;k>=dropingValue;k--)

                      {

                          double data = dataArry[(int) k]; //get the data

                          double weightedValue = data*weight; //calculate the weighted value

                          //Add weighted value to total weighted value

                          totalWeightedValue = totalWeightedValue + weightedValue;

                          dataCount++; //data count increase by 1

                      }

                      //Calculate the average weighted value

                      double totalWeightedAvg = totalWeightedValue/dataCount;

                      //Append all the output message and add it to output list

                      outputData.add(output1+totalWeightedAvg+output2);

                  }

              }

          }

      }

      catch (Exception e)

      {

          e.printStackTrace();

      }

  }

  // Definition of the write method to the output file

  public static void writeFile(String fileName)

  {

      //Check whether the output list is empty or not

      if (outputData != null && outputData.size()>0)

      {

          try (PrintWriter pw = new PrintWriter(new FileWriter(fileName)))

          {

              //iterate the output list to get the output data

              for (int i=0;i<outputData.size();i++)

              {

                  pw.println(outputData.get(i));//write the output data into the output file

              }

          }

          catch (Exception ioe)

          {

              ioe.printStackTrace();

          }

          System.out.println("Output File Created!");

      }

  }

}

Step 2

Content of input file i.e. data.txt

help_outline

Image Transcriptionclose

*data.txt 3 D WeightedAvgDataAnalyzer.java 10.5 3 10 70 90 80 20 2

fullscreen
Step 3

Output 1

Output of the console

...
help_outline

Image Transcriptionclose

Enter the name of input file: data.txt Enter the name of the output file: output.txt Output File Created!

fullscreen

Want to see the full answer?

See Solution

Check out a sample Q&A here.

Want to see this answer and more?

Solutions are written by subject experts who are available 24/7. Questions are typically answered within 1 hour.*

See Solution
*Response times may vary by subject and question.

Related Computer Science Q&A

Find answers to questions asked by student like you
Show more Q&A
add
question_answer

Q: For Javascript, the prompt asks the following: Write a function that uses alert() to display pairs o...

A: Program Approach-1)Create a function named convertTemp () with two parameters lowTemp and highTemp.2...

question_answer

Q: 1:02 PM QWhat is your question? B Consigerrtne two nOstS A aNa B are connected through a direct link...

A: Given data:Bandwidth of the link = 10bits/sec.Propagation speed = 2x10 m/secDistance = 5000 kmConver...

question_answer

Q: when is it apporiate to use object oriented design? when is it apporiate to use sturctured design? a...

A: Object-oriented design: As the name suggests, the programming uses objects. The goal of object-orien...

question_answer

Q: Do the following program in Java Eclipse:A veterinarian services many pets and their owners. As new ...

A: Program Instructions:Create a java program in eclipse and import all required modules.Now create a m...

question_answer

Q: Did I correctly perform the SQL query below (photo attached): Create a query that is based on two ta...

A: The given query is performed correctly:SELECT COURSE_TITLE, COURSE_DESCRIPTION FROM COURSE INNER JOI...

question_answer

Q: Write a complete Python for loop to print the names of all friends in pals on one line separated by ...

A:  Program approach-Lists are like the arrays that have been declared in other languages. A single lis...

question_answer

Q: What type of key is used in symmetric cryptography, must be known by both parties, and is used for b...

A: Symmetric cryptography (Symmetric-key encryption):It is an encryption technique in which a single ke...

question_answer

Q: what is the cpu time when the number of instructions executed by the program is 500, cycles per inst...

A: CPU time (or CPU Execution time) is the time between the start and the finishing(end) of execution o...

question_answer

Q: Define a two-dimension array with 10 rows and 2 columns in java does this look correct? I think I am...

A: The following are the mistakes in the code –The integer j is not declared.The braces are not closed ...