Question

create a new Java application called "WeightedAvgWithExceptions" (without the quotation marks), according to the following guidelines...

create a new Java application called "WeightedAvgWithExceptions" (without the quotation marks), according to the following guidelines and using try-catch-finally blocks in your methods that read from a file and write to a file, as in the examples in the lesson notes for reading and writing text files.

Input File

The input file - which you need to create and prompt the user for the name of - should be called 'data.txt', and it should be created according to the instructions below.

The input file should contain (in order): the weight (greater than 0 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.

For example, you might have these values in your input file (data.txt)...

0.5 3 10 70 90 80 20

Creating the Input file

To create the input file, while in NetBeans with your project open, click to highlight the top-level folder of your project in the projects tab at the upper left. Then starting with the NetBeans File menu, do

File->New File

Keep the Project name at the top; keep Filter blank

For Categories choose Other (at the bottom of the categories list)
For File Types choose Empty File (at the bottom of the files list)

Next

FileName: data.txt

Folder: this should be blank; if it's not, delete whatever's there.

Finish

In the empty file data.txt that you just created, add a single line of data like the one in the example above, where the weight is a double (greater than 0.0 and less than or equal to 1.0) and the other numbers are the number, n, of lowest values to drop, and then the numbers to be averaged after dropping the lowest n values. Then save this data.txt input file.

It's important that your input file is where NetBeans will look to find it. The above instructions should make sure that that happens.

Main Method

Your main method should contain just three lines like these...

ArrayList<Double> inputValues = getData();

double weightedAvg = calcWeightedAvg(inputValues);

printResults(inputValues, weightedAvg);

...where the printResults method should prompt the user for the name of the output file and print to that output file.

Output

Given the sample values above in the data.txt input file, the output file should contain something 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.

Prompting for names of input file and output file

Make sure you prompt the user for the name of the input file (even though we know what it is). Use this prompt: "Enter the filename of "data.txt" (no quotes) for the input file: "

Also prompt the user for the name of the output file. If you use code like that in Horstmann's Total.java program to create the output file, the output file should be located at the same place as the input file. Check the NetBeans Files tab (next to the Project tab in the upper left) to see both the input and output files.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

WeightedAvgWithExceptions.java

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Scanner;

public class WeightedAvgWithExceptions {

public static void main(String[] args) {

  

ArrayList<Double> input = getData();

System.out.println(input);

double weightedAverage = calcWeightedAvg(input);

printResults(input, weightedAverage);

}

public static ArrayList<Double> getData() {

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

Scanner console = new Scanner(System.in);

System.out.println("Enter 'data.txt' (without the quotes) as the name of the input file: ");

String inputFileName = console.next();

File inputFile = new File(inputFileName);

Scanner in = null;

try {

in = new Scanner(inputFile);

while (in.hasNextDouble()) {

inputLine.add(in.nextDouble());

}

} catch (FileNotFoundException fne) {

String errorString = fne.getMessage();

System.out.println("There was an error when trying to read from file "

+ inputFileName + ": " + errorString);

} finally {

if (in != null) {

in.close();

}

}

return inputLine;

}

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

double enteredWeight = Double.parseDouble(data.get(0).toString());

int numberofLowetValuesDropped =(int) Double.parseDouble(data.get(1).toString());

data.remove(1);

data.remove(0);

Collections.sort(data);

double total = 0;

for(int i=numberofLowetValuesDropped; i<data.size(); i++){

total = total + Double.parseDouble(data.get(i).toString());

}

data.add(0, enteredWeight);

data.add(1, Double.valueOf(numberofLowetValuesDropped));

double avg = total/(data.size() - numberofLowetValuesDropped);

return avg;

  

}

public static void printResults(ArrayList<Double> inputList, double weightedAvg) {

Scanner console = new Scanner(System.in);

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

String outputFileName = console.next();

PrintWriter out = null;

if (inputList.size() > 0) { // we have a non-empty inputList

try {

out = new PrintWriter(outputFileName);

String s = "The weighted average of the numbers is "+weightedAvg+", " +

"when using the data "+inputList+", where "+inputList.get(0)+" is the weight used, " +

"and the average is computed after dropping the lowest "+inputList.get(1)+" values.";

out.print(s);

System.out.println("Your output is in the file " + outputFileName + ".");

} catch (FileNotFoundException fne) {

String errorString = fne.getMessage();

System.out.println("There was an error when trying to write to the output file "

+ errorString);

} finally {

if (out != null) {

out.close();

}

}

} else {

System.out.println("Problems reading data from input file; no output written to " + outputFileName);

}

}

  

}

Output:

Enter 'data.txt' (without the quotes) as the name of the input file:
D:\\data.txt
[0.5, 3.0, 10.0, 70.0, 90.0, 80.0, 20.0]
Enter the name of the output file:
D:\\output.txt
Your output is in the file D:\\output.txt.

data.txt

0.5 3 10 70 90 80 20

output.txt

The weighted average of the numbers is 42.5, when using the data [0.5, 3.0, 10.0, 20.0, 70.0, 80.0, 90.0], where 0.5 is the weight used, and the average is computed after dropping the lowest 3.0 values.

Add a comment
Know the answer?
Add Answer to:
create a new Java application called "WeightedAvgWithExceptions" (without the quotation marks), according to the following guidelines...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • create a new Java application called "WeightedAvgDataAnalyzer" (without the quotation marks), that modifies the DataAnalyzer.java in...

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

  • The input file should be called 'data.txt' and should be created according to the highlighted instructions...

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

  • create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

    create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the...

  • create a new Java application called "RecursiveTriangle" (without the quotation marks) according to the following guidelines....

    create a new Java application called "RecursiveTriangle" (without the quotation marks) according to the following guidelines. Modify the example in Horstmann Section 5.9, pp. 228-230 so that the triangle displays “in reverse order” as in the example below, which allows the user to set the number of lines to print and the String used for printing the triangle. Use a method to prompt the user for the number of lines (between 1 and 10) to print. This method should take...

  • I've been assigned to create a new Java application called "CheckString" (without the quotation marks) according...

    I've been assigned to create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the...

  • The input file should contain (in order): the weight (a number greater than zero and less...

    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. The program should also write to an output file (rather than the console, as in Horstmann). So you should also prompt the user for the name of the output file, and then print your results to an output file...

  • create a new Java application called "MinMax" (without the quotation marks) that declares an array of...

    create a new Java application called "MinMax" (without the quotation marks) that declares an array of doubles of length 5, and uses methods to populate the array with user input from the command line and to print out the max (highest) and min (lowest) values in the array.

  • Create a java project. Create a class called cls2DarrayProcessor.java. with the following: Reads numbers from a...

    Create a java project. Create a class called cls2DarrayProcessor.java. with the following: Reads numbers from a pre-defined text file. A: Text file name should be data.txt B: Text file should be in the same workspace directory of your project's folder C: Text file name should be STORED in a String and called: String strFile ='./data.txt' Defines a 2-D array of integers with dimensions of 5 rows by 5 columns. Inserts the data from the text file to the 2-D array...

  • Write a menu based program implementing the following functions: (0) Write a function called displayMenu that...

    Write a menu based program implementing the following functions: (0) Write a function called displayMenu that does not take any parameters, but returns an integer representing your user's menu choice. Your program's main function should only comprise of the following: a do/while loop with the displayMenu function call inside the loop body switch/case, or if/else if/ ... for handling the calls of the functions based on the menu choice selected in displayMenu. the do/while loop should always continue as long...

  • java Part 1 Create a NetBeans project that asks for a file name. The file should...

    java Part 1 Create a NetBeans project that asks for a file name. The file should contain an unknown quantity of double numeric values with each number on its own line. There should be no empty lines. Open the file and read the numbers. Print the sum, average, and the count of the numbers. Be sure to label the outputs very clearly. Read the file values as Strings and use Double.parseDouble() to convert them. Part 2 Create a NetBeans project...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT