Question

In: Computer Science

In java, follow the methods in bold First, launch NetBeans and close any previous projects that...

In java, follow the methods in bold

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.

WeightedAvgDataAnalyzer PA

This assignment builds off of an example in Horstmann (called DataAnalyzer) which supplies you with

some code for giving the user multiple opportunities for entering a correct file name, and the previous

PA WeightedAvgDropSmallest. This PA should use ArrayLists.

Create an input file called ‘data.txt’ (see directions at the bottom of the PA description).

Even though you create a specific input file with a name, prompt the user for a filename. The file should

contain a weight value (type double, between 0 and 1); the number of lowest values to drop, and the

numbers to be averaged (after dropping the lowest values).

Contents of an input file called data.txt might look something like:

0.5 3 10 70 90 80 20

In main use a while loop like the one used in the Horstman example which allows the user to re-enter

the input file name (this allows for testing exceptions). Below, I have used the Horstmann loop

structure. Modify the code to use ArrayLists instead of arrays. Instead of computing the sum in the

Horstmann example, do a call to a method which is very similar to the one in the

WeightedAvgDropSmallest PA. Also, prompt the user for an output file name. And, call another method

to write the contents of the output file.

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

boolean done = false;

while (!done) {

try {

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

String infileName = in.next();

// Declare an ArrayList of type double on left side of

// assignment statement for readFile(infileName) call.

// readFile will fill the ArrayList with values from the input file.

// for example:

ArrayList<Double> data = readFile(infileName);

// Call a method to calculate the weighted average and return it as type double

// to main, similar to code in WeightedAvgDropSmallest

// for example:

double weightedAvg = calcWeightedAvg(data);

// Print out the weighted average.

// Prompt user for an output file name and read it into a String variable.

// Call a method to write the file, pass three parameters:

// the file name, the ArrayList containing the values, the weighted average.

// for example:

WriteFile(outfileName, data, weightedAvg);

// The contents of the output file should look like (see below, out.txt)

done = true;

// example catches

} catch (FileNotFoundException exception) {

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

} catch (IOException exception) {

exception.printStackTrace();

}

}

}

Example contents of output file called out.txt (this can be all in one line):

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.

6

Here’s the example run using the input file above called data.txt and output file called out.txt

run:

Enter the input file name: data.txt

weighted average = 42.5

Enter the output file name: out.txt

Writing to file

BUILD SUCCESSFUL (total time: 27 seconds)

The other methods:

You will be able to reuse some of the code in the Horstmann readFile method but in this case the

method needs to return an ArrayList of type Double. The input file name is passed in as a parameter

For example the method header might look like below:

public static ArrayList<Double> readFile(String filename) throws IOException

Not too much can be reused from the Horstmann readData method. Instead, the method needs to

return an ArrayList of type Double. Use a while loop with a condition hasNextDouble() to keep checking

for the last value in the input file. Inside the while loop is your call to nextDouble() – we have used this

before. Notice in the header, the Scanner object declared in readFile method is passed in as a parameter

(same as in Horstmann).

public static ArrayList<Double> readData(Scanner in) throws IOException

Example header for the method that actually calculates the weighted average. The filled ArrayList (with

values from the input file) is passed as a parameter. The method returns the weighted average to main:

public static double calcWeightedAvg(ArrayList<Double> data)

Here’s an example method header that writes to the output file. Notice the three parameters. There are

different approaches, I used the PrintWriter class and declared a new PrintWriter within the ‘try’

condition (see below):

public static void WriteFile(String outfile, ArrayList<Double> data, double weightedAvg) throws

FileNotFoundException {

try (PrintWriter outs = new PrintWriter(new FileOutputStream(outfile))) {

outs.printf("The weighted . . . .

// for loop that reads the elements in the ArrayList called data

Solutions

Expert Solution

/******************************DataAnalyzer.java********************************/

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class DataAnalyzer {

   public static void main(String[] args) {

       Scanner in = new Scanner(System.in);

       boolean done = false;

       while (!done) {

           try {

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

               String infileName = in.next();

               // Declare an ArrayList of type double on left side of

               // assignment statement for readFile(infileName) call.

               // readFile will fill the ArrayList with values from the input file.

               // for example:

               ArrayList<Double> data = readFile(infileName);

               // Call a method to calculate the weighted average and return it as type double

               // to main, similar to code in WeightedAvgDropSmallest

               // for example:

               double weightedAvg = calcWeightedAvg(data);

               // Print out the weighted average.

               // Prompt user for an output file name and read it into a String variable.

               System.out.print("Enter output file name: ");
               String outfileName = in.next();

               // Call a method to write the file, pass three parameters:

               // the file name, the ArrayList containing the values, the weighted average.

               // for example:

               writeFile(outfileName, data, weightedAvg);

               // The contents of the output file should look like (see below, out.txt)

               done = true;

               // example catches

           } catch (FileNotFoundException exception) {

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

           } catch (IOException exception) {

               exception.printStackTrace();

           }

       }

   }

   //method readFile()
   public static ArrayList<Double> readFile(String filename) throws IOException {

       ArrayList<Double> data = new ArrayList<>();

       File file = new File(filename);
       Scanner sc = new Scanner(file);
       // while loop till file has line
       while (sc.hasNextDouble()) {
           // read the line
           double value = sc.nextDouble();

           data.add(value);
       }
       sc.close();
       return data;
   }

   //method calcWeightedAvg()
   public static double calcWeightedAvg(ArrayList<Double> data) {

       double weightedAvg, total = 0;
       double weight = data.remove(0);
       data.trimToSize();
       double droppedValues = data.remove(0);
       data.trimToSize();
       Collections.sort(data);
       Collections.reverse(data);

       for (int i = 0; i < droppedValues; i++) {

           data.remove(data.size() - 1);
           data.trimToSize();

       }

       for (Double double1 : data) {

           total += double1 * (weight);
       }
       weightedAvg = total / data.size();
       return weightedAvg;
   }

   //method writeFile()
   public static void writeFile(String outfile, ArrayList<Double> data, double weightedAvg) throws

   FileNotFoundException {

       try (PrintWriter outs = new PrintWriter(new FileOutputStream(outfile))) {

           outs.printf("The weighted average is: %s", weightedAvg);
       }
   }
}

/*************************output*****************************/

Please let me know if you have any doubt or modify the answer, Thanks :)


Related Solutions

First, launch NetBeans and close any previous projects that may be open (at the top menu...
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 "AverageWithMethods" (without the quotation marks) according to the following guidelines. The program prompts the user for five to ten numbers, all on one line, and separated by spaces. Then the user calculates the average of those numbers, and displays the numbers and their average to the user. The program uses...
First, launch NetBeans and close any previous projects that may be open (at the top menu...
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 "AtmSimulator" (without the quotation marks) (not ATMSimluator!) that simulates a simple one-transaction ATM according to the following guidelines. The program should start with an initial account balance, which you can set to any legitimate double value. All output of currency values should include a leading dollar sign and use two...
this a continuation of my previous question. answer with Java programming language and Netbeans idk 1,...
this a continuation of my previous question. answer with Java programming language and Netbeans idk 1, 2, 3, 4) CODE class Device { private String serialNumber, color, manufacturer; private double outputPower; public Device () { serialNumber = ""; color = ""; manufacturer = ""; outputPower = 0.0; } public Device(String serialNumber, String color, String manufacturer, double outputPower) { this.serialNumber = serialNumber; this.color = color; this.manufacturer = manufacturer; this.outputPower = outputPower; } public String getSerialNumber() { return serialNumber; } public void...
USING JAVA (netbeans) In your main, ask the user for an int. Do this by first...
USING JAVA (netbeans) In your main, ask the user for an int. Do this by first printing a request for the int, then creating an int x, and using the Scanner to read an int from the user and put it in x, like this: int x = scan.nextInt(); ☑ Next read in two doubles d1 and d2 from the user. This will look a lot like what you did for the int, but the scanner reads doubles using scan.nextDouble();...
Language: Java I have written this code but not all methods are running. First method is...
Language: Java I have written this code but not all methods are running. First method is running fine but when I enter the file path, it is not reading it. Directions The input file must be read into an input array and data validated from the array. Input file format (500 records maximum per file): comma delimited text, should contain 6 fields: any row containing exactly 6 fields is considered to be invalid Purpose of this code is to :...
Complete the java program. /* Note: Do not add any additional methods, attributes. Do not modify...
Complete the java program. /* Note: Do not add any additional methods, attributes. Do not modify the given part of the program. Run your program against the provided Homework2Driver.java for requirements. */ /* Hint: This Queue implementation will always dequeue from the first element of the array i.e, elements[0]. Therefore, remember to shift all elements toward front of the queue after each dequeue. */ public class QueueArray<T> { public static int CAPACITY = 100; private final T[] elements; private int...
Write a JAVA program called Convertor that has two methods. The first one converts an input...
Write a JAVA program called Convertor that has two methods. The first one converts an input binary into its equivalent decimal number. The second method converts a decimal number into its equivalent binary.​ binary2Decimal, decimal2Binary are the names for those methods.​ binary2Decimal receives a binary number as a string and returns a decimal number as an integer. And vice versa for the decimal2Binary method.​
Write a class with 2 methods. The first method determines if any two sides added together...
Write a class with 2 methods. The first method determines if any two sides added together are greater than the remaining side. The second method calculates the triangle’s area. // Method 1: If sum of any two sides is greater than the remaining side, return true public static boolean isValid(double sid1, double side2, double side3) // Method 2: Returns the triangle area public static double area(double side1, double side2, double side3) Develop a test program that takes in the three...
Write a java program to accept a telephone number with any number of letters. The output should display a hyphen after first 3 digits and subsequently a hyphen (-) after very four digits.
Write a java program to accept a telephone number with any number of letters. The output should display a hyphen after first 3 digits and subsequently a hyphen (-) after very four digits. Also, modify the program to process as many telephone numbers as the user wantscode optimization: no unnecessary variables , if statements and counterssample output screen shown with 3 cases(atleast one with blank spaces ect.)Descriptive block and inline comments include.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT