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.)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.
Notes
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. Some of the Horstmann code can be reused. 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 numbers to drop, and the numbers to be averaged after dropping.
Contents of an input file called data.txt might look something like:
0.5 2 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 fileName = in.next();
// Declare an ArrayList of type double on left side of
// assignment statement for readFile(fileName) call.
// readFile will fill the ArrayList with values from the input file.
// Call a method to calculate the weighted average and return it as type double
// to main, similar to code in WeightedAvgDropSmallest
// 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.
// The contents of the output file should look like (see below)
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 40.0, when using the data 35.0, 45.0, 40.0,
where 0.5 is the weight used, and the average is computed after dropping the lowest 2 values.
Here’s the example run using input file above called data.txt and output file called out.txt
run:
Enter the input file name: data.txt
weighted average = 40.0
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 outputfile. Notice the three parameters. There are difference 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 accesses the elements in the ArrayList called data
// . . .
}
}
Cde:
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;
/**
*
* @author pc
*/
public class WeightedAvgDataAnalyzer {
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 fileName = in.next();
// Declare an ArrayList of type double on left side of
// assignment statement for readFile(fileName) call.
ArrayList<Double> arl=readFile(fileName);
// readFile will fill the ArrayList with values from the input
file.
// Call a method to calculate the weighted average and return it
as type double
double result=calcWeightedAvg(arl);
// to main, similar to code in WeightedAvgDropSmallest
// Print out the weighted average.
System.out.println("Weighted Average = "+result);
// Prompt user for an output file name and read it into a String
variable.
System.out.println("Enter the output file name: ");
fileName=in.next();
// Call a method to write the file, pass three parameters:
// the file name, the ArrayList containing the values, the weighted
average.
writeFile(fileName,arl,result);
// The contents of the output file should look like (see below)
done = true;
// example catches
} catch (FileNotFoundException exception) {
System.out.println("File not found");
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
public static ArrayList<Double> readFile(String fileName)
throws IOException{
Scanner in=new Scanner(new File(fileName));//open file
return readData(in);//call readData
}
public static ArrayList<Double> readData(Scanner in) throws
IOException
{//create arraylist
ArrayList<Double> list =new ArrayList<Double>();
//read file into list
while(in.hasNextDouble())
{
double value=in.nextDouble();
list.add(value);//add values
}
return list;
}
public static double calcWeightedAvg(ArrayList<Double>
data)
{//create new arraylist as we will be sorting values in the
arraylist as we dont want the real arraylist to get sorted (we
will
//need that in writeFile method so sort int a temporary
araylist
ArrayList<Double> list=new ArrayList<Double>();
//copy into new one
for(int i=0;i<data.size();i++)
{
list.add(data.get(i));
}
//find weight
double weight=list.get(0);
int drop=list.get(1).intValue();//drop value
list.remove(0);//remove drop and weight from list
list.remove(1);
Collections.sort(list);//now sort remaining data
double weAvg=0;
//by leaving first 'drop' values find the weeight average
for(int i=drop;i<list.size();i++)
{
weAvg+=list.get(i);
}
weAvg*=weight;//multiply by weight
weAvg=weAvg/(list.size()-drop);//and divide by number of values
(total - dropped)
return weAvg;
}
public static void writeFile(String outfile, ArrayList<Double> data, double weightedAvg) throws FileNotFoundException {
System.out.println("Writing to file");
try (PrintWriter outs = new PrintWriter(new
FileOutputStream(outfile))) {
outs.printf("The weighted average of the numbers is
"+weightedAvg+", when using the data ");
for(int i=2;i<data.size();i++)//printing data
{
outs.printf(data.get(i)+", ");
}
outs.printf("where "+data.get(0)+" is the weight used, and the
average is computed after dropping the lowest "+data.get(1)+"
values.");
// for loop that accesses the elements in the ArrayList called
data
// . . .
}
}
}
Output:
'
create a new Java application called "WeightedAvgDataAnalyzer" (without the quotation marks), that modifies the DataAnalyzer.java in...
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 "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...
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 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...
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 "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...
create a new Java application called "Scorer" (without the quotation marks) that declares a two-dimensional array of doubles (call it scores) with three rows and three columns and that uses methods and loops as follows. Use a method containing a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Use a method containing a nested for loop to compute the average of the doubles in each row. Use a method to...
7.2 Write a Java program called to create an Excel spreadsheet Create a class called Food to represent a Lunch food item. Fields include name, calories, carbs In a main method (of a different class), ask the user "How many things are you going to eat for lunch?". Loop through each food item and prompt the user to enter the name, calories, and grams of carbs for that food item. Create a Food object with this data, and store each...
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.
(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...