Question

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

Creating the Input File

To create the input file, while in NetBeans with your project open, first click to highlight the top-level folder of your project, which should be called WeightedAvgDataAnalyzer.

Then from the File menu do this:

File->New File

Keep the Project name at the top; keep Filter blank

Categories choose Other (at the bottom of the categories list)
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 that shown 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.

Code In Java

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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class WeightedAvgDataAnalyzer {
public static LinkedList<LinkedList<Double>> inputDataList = new LinkedList<LinkedList<Double>>();//LinkedList to store input data
public static LinkedList<String> outputDataList = new LinkedList<String>();//LinkedList to store calculated data
public static void main(String[] args) {
Scanner userInput = null;// User Input Scanner
try {
userInput = new Scanner(System.in);// User Input Scanner
//Iterating infinite loop till user enters correct input file
while (true) {
System.out.println("Pleasee Enter Input File Name:");
String inFileName = userInput.next(); //Getting Input File Name from user
File file = new File(inFileName); //Creating File object using Input File Name
//Checking weather file is exists or not
if (file.exists()) {
readData (inFileName); //Reading data from input text file and creating data list
break;//terminating infinite loop
} else {
throw new FileNotFoundException("File not Found!");
}
}
System.out.println("Pleasee Enter Output File Name:");
String outFileName = userInput.next(); //Getting Out File Name from user
calculateWeightedAvg(); //Calculating Average Weighted Value of input data
writeFile (outFileName);//Writing Average Weighted Value to output file
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (userInput != null) {
userInput.close();//closing scanner
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// This method is to read input file
public static void readData(String fileName) {
//try-with-resources statement to read input file
try (Scanner scanner = new Scanner(new File(fileName))) {
//Iterating scanner for each line of input text file
while (scanner.hasNextDouble()) {
String line = scanner.nextLine();// getting new line from text file
String[] lineArray = line.trim().split("\\s+");// Splitting each line by space to get string array
LinkedList<Double> subDataList = new LinkedList<Double>();//Creating sublist for each line of input text file
subDataList.add(Double.parseDouble(lineArray[0])); //Adding weight into list
subDataList.add(Double.parseDouble(lineArray[1])); //Adding dropping value
//Iterating loop to get Data from line
for (int i=2;i<lineArray.length;i++) {
subDataList.add(Double.parseDouble(lineArray[i])); //Adding rest of the data
}
inputDataList.add(subDataList);//adding sub list into actual list
}
} catch (Exception e) {
e.printStackTrace();
}
}
// This method will calculate weighted average data and storing it to output list
public static void calculateWeightedAvg () {
try {
//Checking weather input list is not empty
if (inputDataList != null && inputDataList.size()>0) {
//Iterating input list
for (int i=0;i<inputDataList.size();i++) {
LinkedList<Double> subDataList = inputDataList.get(i);//Getting each sublist
//Checking weather sublist is not empty
if (subDataList != null && subDataList.size()>0) {
String outputMsg1 = "The weighted average of the numbers is ";//Creating output message
String outputMsg2 = " when using the data ";//Creating output message
Double weight = subDataList.get(0);//Getting weight
Double dropingValue = subDataList.get(1);//Getting dropping value
Double[] dataArry = new Double[subDataList.size()-2];//Creating Data Array
int dataCount = 0;//Declaring data count as zero
//iterating loop to get data and adding them into double array
for (int j=2;j<subDataList.size();j++) {
outputMsg2 = outputMsg2 + subDataList.get(j) +", ";//Creating output message
dataArry[dataCount] = subDataList.get(j);//adding data in array
dataCount++;//increasing data count by 1
}
outputMsg2 = outputMsg2+"where "+weight+ " is the weight used, and the average " +
"is computed after dropping the lowest "+dropingValue+" values.";//Creating output message
Arrays.sort(dataArry);//Sorting data array
double totalWeightedValue = 0;//Declaring total Weighted Value
dataCount = 0;//setting data count as zero again for below use
//Below loop will iterate till dropping values reached in the array
for (double k=(int)dataArry.length-1;k>=dropingValue;k--) {
double data = dataArry[(int) k]; //getting data
double weightedValue = data*weight; //calculating weighted value
totalWeightedValue = totalWeightedValue + weightedValue; //adding weighted value to total weighted value
dataCount++; //data count increase by 1
}
double totalWeightedAvg = totalWeightedValue/dataCount;//calculating average weighted value
outputDataList.add(outputMsg1+totalWeightedAvg+outputMsg2); //finally appending all the output message and adding it to output list
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// This method is to write to output file
public static void writeFile(String fileName) {
//Checking weather output list is not empty
if (outputDataList != null && outputDataList.size()>0) {
//try-with-resources statement to write in output file
try (PrintWriter pw = new PrintWriter(new FileWriter(fileName))) {
//iterating output list to get output data
for (int i=0;i<outputDataList.size();i++) {
pw.println(outputDataList.get(i));//writting output data into output file
}
} catch (Exception ioe) {
ioe.printStackTrace();
}
System.out.println("Output File Created!");
}
}
}

OUTPUT:

Console X <terminated> WeightedAvgData Analyzer (Java Application CA Program FilesVavajre7bir Pleasee Enter Input File Name:

data.txt - Notepad File Edit Format View Help 0.5 3 10 70 90 80 20 output.txt - Notepad File Edit Format View Help The weight

Add a comment
Know the answer?
Add Answer to:
The input file should be called 'data.txt' and should be created according to the highlighted instructions...
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 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 "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...

  • C++ (1) Write a program to prompt the user for an input and output file name....

    C++ (1) Write a program to prompt the user for an input and output file name. The program should check for errors in opening the files, and print the name of any file which has an error, and exit if an error occurs. For example, (user input shown in caps in first line, and in second case, trying to write to a folder which you may not have write authority in) Enter input filename: DOESNOTEXIST.T Error opening input file: DOESNOTEXIST.T...

  • 2. Read in an unknown number of real values from a file called “data.txt”. Calculate the...

    2. Read in an unknown number of real values from a file called “data.txt”. Calculate the average of the real numbers. Output the average of the real numbers to a file called “output.txt”. Some skeleton code is provided for you below. #include    int main (void) {                         FILE *infile = NULL;                         FILE *outfile = NULL;                         /* Fill in the code to open a file. Make sure you check that the file was open successfully. */                         while (!feof (infile))                         {                                     /*...

  • and save it in the same folder as your source Download file: data.txt code file. data.txt...

    and save it in the same folder as your source Download file: data.txt code file. data.txt contains a list of client's account number, client's name and their balance. Write a C program to read rows of data from the file and store them in the arrays. Display the list of client's account number, client's name and the client's balance on the screen in reverse order. The program should write the data in reverse order (without header) to another file called...

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

  • (Java) Rewrite the following exercise below to read inputs from a file and write the output...

    (Java) Rewrite the following exercise below to read inputs from a file and write the output of your program in a text file. Ask the user to enter the input filename. Use try-catch when reading the file. Ask the user to enter a text file name to write the output in it. You may use the try-with-resources syntax. An example to get an idea but you need to have your own design: try ( // Create input files Scanner input...

  • Write a PYTHON program that reads a file (prompt user for the input file name) containing...

    Write a PYTHON program that reads a file (prompt user for the input file name) containing two columns of floating-point numbers (Use split). Print the average of each column. Use the following data forthe input file: 1   0.5 2   0.5 3   0.5 4   0.5 The output should be:    The averages are 2.50 and 0.5. a)   Your code with comments b)   A screenshot of the execution Version 3.7.2

  • There is a file called mat2.txt in our files area under the Assignments folder. Download it...

    There is a file called mat2.txt in our files area under the Assignments folder. Download it and save it in the same folder where this Matlab file (HW08_02.m) is saved. It may be worth opening that text file to see how it is set out. Note well, however, that the file might have a different number of lines and different number of numbers on each line. Write a Matlab program that does the following: Prompt the user for an input...

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