Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, this is my assignment that I need help with! : Write a program that write

ID: 3707665 • Letter: H

Question

Hello, this is my assignment that I need help with! :

Write a program that writes user supplied data to a text file and can perform a few statistical calculations on the data.

Constraints

The file directory will be C:/W12Assignment. Mac and Linux distro users can modify this location

Only one file will be created, used, and updated while the program runs

Requirements

Use exception handling and validation where appropriate

Use PrintWriter and Scanner for writing and reading data

Use a separate (external to the main class) subclass to write data

Use a separate (external to the main class) subclass to read data

Use a separate (external to the main class) subclass to validate entries

Use set and get methods in the subclasses

Find the average of all the numbers in the file

Find the smallest number in the file

Find the largest number in the file

Find the standard deviation (StdDev) of the number set (Follow the “Basic Example” as a model for your StdDev algorithm located here (Links to an external site.)Links to an external site..)

Implement a loop to run the program again if the user wishes (Note: this will only allow updates

or reading of the same file since only one file is used for duration of the program run)

Use the supplied MyNumbersLarge.txt file to make sure you are obtaining the correct information as such:

o All numbers printed (500 numbers)
o The average of the numbers in file name is: 502.3212
o The smallest number in the file is: 1.2416
o The largest number in the file is: 999.3116
o The standard deviation for the numbers in this file is: 287.6556

This program will utilize code learned from Week 1 through Week 12

Hints

Consider using an ArrayList of Doubles to store numbers as they are entered

Research "Collections" to assist with minimums and maximums

Considering writing the code to work with all correct entries before implementing validation and exception handling. Once the code works, then try to break it with bad entries. This way, you can separate the requirements (Code in chunks!)

Make sure you use Java coding conventions

Expected Output

Welcome to My Statistics Calculator Enter the name of your text file (e.g. MyNumbers) The file extension will be added after entry. ->: MyNumbers
The directory does not exist. Creating directory... Directory created at this location ->: C:W12Assignment
The file does not exist. Creating file... File created at this location ->: C:W12AssignmentMyNumbers.txt
Please select from the following menu of options: 1. Enter Data 2. Read Data 3. Exit ->: 2
The file contains no data. Enter data? ->: n

Would you like to run the program again? ->: y
Please select from the following menu of options: 1. Enter Data 2. Read Data 3. Exit ->: 1
How many numbers would you like to send to the file? ->: 6

Enter number 1 -> 89.635

Enter number 2 -> 100.3069

Enter number 3 -> 101.0009

Enter number 4 -> 95.365

Enter number 5 -> 99.3644

Enter number 6 -> 90.00049

Would you like to read the see the results? ->: y

The numbers in this file are: 89.6350

100.3069

101.0009

95.3650

99.3644

90.0005

The average of the numbers in file name is: 95.9455

The smallest number in the file is: 89.6350

The largest number in the file is: 101.0009

The standard deviation for the numbers in this file is: 4.6863

Would you like to run the program again? ->: y

Please select from the following menu of options:

1. Enter Data

2. Read Data

3. Exit ->: 2


The numbers in this file are:

89.6350

100.3069

101.0009

95.3650

99.3644

90.0005

The average of the numbers in file name is: 95.9455

The smallest number in the file is: 89.6350

The largest number in the file is: 101.0009

The standard deviation for the numbers in this file is: 4.6863

Would you like to run the program again? ->: y


Please select from the following menu of options:

1. Enter Data

2. Read Data

3. Exit ->: 1


How many numbers would you like to send to the file? ->: 3

Enter number 1 -> 789.36

Enter number 2 -> 790.46

Enter number 3 -> 698.99

Would you like to read the see the results? ->: y

The numbers in this file are: 789.3600

790.4600

698.9900

The average of the numbers in file name is: 235.6064

The smallest number in the file is: 89.6350

The largest number in the file is: 790.4600

The standard deviation for the numbers in this file is: 179.6279

Would you like to run the program again? ->: n

Thank you for using the program! Good Bye!

Explanation / Answer

I have implemented your code.. There is a small error in output you have provided The error is in these below lines: -

How many numbers would you like to send to the file? ->: 3

Enter number 1 -> 789.36

Enter number 2 -> 790.46

Enter number 3 -> 698.99

Would you like to read the see the results? ->: y

The numbers in this file are: 789.3600

790.4600

698.9900

The average of the numbers in file name is: 235.6064

The smallest number in the file is: 89.6350

The largest number in the file is: 790.4600

The standard deviation for the numbers in this file is: 179.6279

Would you like to run the program again? ->: n

Two errors here are: -

1. You are displaying stats like smallest number , largest number, average and standard deviation of previous 6 numbers and these 3 new numbers combined. but while reading you are just displaying the new 3 entries.

2. The value of average and stadard deviation is wrong as per calculation of all 9 numbers.

So I am assuming we need to have all 9 numbers in the file and every time we enter data we append the data in already existing file.

Please let me know if my assumptiuon is wrong. I will help you to correct the code. Please add import statements if missing

Below is your code: -

WriteData.java

//Begin Subclass WriteData

class WriteData {

// Instance variables

private File fFile; // variable for file

private File fDir; // variable for file directory

/**

*

* Method SetData: Used to write data passed in the form of an ArrayList

*

* into a data file.

*

*

*

* @param fileDir

*

* @param file

*

* @param nums

*

* @param max

*

* @throws FileNotFoundException

*

*/

public void setData(File fileDir, File file, ArrayList<Double> nums, int max) throws FileNotFoundException {

fFile = file;

fDir = fileDir;

int flag = 1; // Flag variable

// Write data to the file

try (PrintWriter output = new PrintWriter(fFile)) {

for (double i : nums) {

if (flag < max) {

output.printf("%.4f" + System.getProperty("line.separator"), i);

flag += 1;

} else {

output.printf("%.4f", i);

}

}

output.close();

}

}

} // End Subclass WriteData

ReadData.java

//Begin Subclass ReadData

class ReadData {

// Instance variables

private File fFile; // variable for file

private File fDir; // variable for file directory

private double avg = 0; // variable for average

ArrayList<Double> nums = new ArrayList<Double>(); // Used for numbers

ArrayList<Double> sdNums = new ArrayList<Double>(); // Used for standard

// deviation calculation

private double max; // variable for maximum value

private double min; // variable for maximum value

private double avg_copy = 0; // variable for average

private double avgSqrdDiff = 0; // variable for average of squared

// differences

private double stdDev = 0; // variable for standard deviation

// SET

// METHODS*******************************************************************

/**

*

* Method setData: Method to read numbers from the file and place them into

*

* an ArrayList. The list is then sent to the other set methods

*

*

*

* @param fileDir

*

* @param file

*

* @throws FileNotFoundException

*

*/

public void setData(File fileDir, File file) throws FileNotFoundException {

fFile = file;

fDir = fileDir;

// Clear the nums arraylist for input of new numbers

nums.clear();

// Try adding data to the arraylist

try (Scanner input = new Scanner(fFile)) {

while (input.hasNextLine()) {

nums.add(input.nextDouble());

}

}

// Set average of numbers

setAvg(nums);

// Set min and max

setMinMax(nums);

// Set standard deviation

setStdDev(nums);

}

/**

*

* Method setAvg: Used to calculate the average of the numbers in the file

*

*

*

* @param nums

*

*/

private void setAvg(ArrayList<Double> nums) {

avg = 0;

// Calculate sum for numbers

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

avg += nums.get(i);

// Calculate and set average

avg /= nums.size();

}

/**

*

* Method setMinMax: Determine min and max values of data in file

*

*

*

* @param nums

*

*/

private void setMinMax(ArrayList<Double> nums) {

max = Collections.max(nums); // Finds the highest number in the set

min = Collections.min(nums); // Finds the lowest number in the set

}

/**

*

* Method setStdDev: Used to determine the StdDev for the file data

*

*

*

* @param nums

*

*/

private void setStdDev(ArrayList<Double> nums) {

/* Reset variables */

avg_copy = 0;

avgSqrdDiff = 0;

stdDev = 0;

/* reset array */

sdNums.clear();

/* Get Mean/Average of numbers */

avg_copy = getAvg();

/**

*

* Calculate deviations for each number and place the results into a new

*

* ArrayList.

*

*/

for (double i : nums) {

i -= avg_copy;

sdNums.add(pow(i, 2));

}

/**

*

* Get Mean/Average of numbers in new ArrayList

*

*/

for (double x : sdNums) {

avgSqrdDiff += x;

}

/**

*

* Find variance which is mean/average of new ArrayList

*

*/

avgSqrdDiff /= sdNums.size();

/**

*

* The population standard deviation = SQRT of variance

*

*/

stdDev = sqrt(avgSqrdDiff);

}

// GET

// METHODS*******************************************************************

/**

*

* Method getAvg: Return the calculated average

*

*

*

* @return avg

*

*/

public double getAvg() {

return avg;

}

/**

*

* Method getMax: Return max value

*

*

*

* @return max

*

*/

public double getMax() {

return max;

}

/**

*

* Method getMin: Return min value

*

*

*

* @return min

*

*/

public double getMin() {

return min;

}

/**

*

* Method getStdDev: return calculated StdDev

*

*

*

* @return sd

*

*/

public double getStdDev() {

return stdDev;

}

} // End Subclass ReadData

CheckErrors.java

//Begin Subclass CheckErrors

public class CheckErrors {

// Instance variables

private boolean flag;

// SET METHODS**********************************************

/**

*

* Method setYesNo: Used to set result for checking proper entry of Yes or

*

* No to continue program. Method is overloaded

*

*

*

* @param ans

*

* @param exit

*

*/

public void setYesNo(String ans, boolean exit) {

// If not either y of n

if (!(ans.equalsIgnoreCase("Y") || ans.equalsIgnoreCase("N"))) {

System.err.println("Exception! Please enter only a Y for Yes or an N for No.");

flag = false;

} else if (ans.equalsIgnoreCase("y")) {

System.out.println();

flag = true;

} else if (ans.equalsIgnoreCase("n") && !exit) {

System.out.println();

flag = true;

} else {

System.out.println("Thank you for using the program! Good Bye!");

flag = true;

}

}

/**

*

* Method setYesNo: Used to set result for checking proper entry of Yes or

*

* No

*

*

*

* @param ans

*

*/

public void setYesNo(String ans) {

if (!(ans.equalsIgnoreCase("Y") || ans.equalsIgnoreCase("N"))) {

System.err.println("Exception! Please enter only a Y for Yes or an N for No.");

flag = false;

} else if (ans.equalsIgnoreCase("y")) {

flag = true;

} else {

flag = false;

}

}

/**

*

* Method setRange: Used to set method to check for menu range

*

*

*

* @param x

*

* @param minVal

*

* @param maxVal

*

*/

public void setRange(int x, int minVal, int maxVal) {

if ((x < minVal) || (x > maxVal)) {

System.out.println("Please enter a choice between " + minVal + " and " + maxVal + " (both inclusive");

flag = false;

} else {

flag = true;

}

}

// GET METHODS***************

/**

*

* Method getYesNo: Return boolean value for loop in main that checks for

*

* proper entry

*

*

*

* @return

*

*/

public boolean getYesNo() {

return flag;

}

/**

*

* Method getRange: Return boolean value for menu range checking

*

*

*

* @return

*

*/

public boolean getRange() {

return flag;

}

} // End Subclass CheckErrors

W12Assignment.java

//Begin Class W12Assignment

public class W12Assignment {

/**

*

* Declare some static variables and objects so they may have class-wide

*

* scope

*

*/

static Scanner sc = new Scanner(System.in);

/**

*

* Subclass declarations. Declare the three subclasses

*

*/

static ReadData rData = new ReadData();

static WriteData wData = new WriteData();

static CheckErrors chkErr = new CheckErrors();

/*

*

* Class-wide variables here

*

*/

// variable for answer loop (to rerun)

static String ans;

static final File FILE_DIR = new File(

"C:/W12Assignment"); /* Default directory */

static File file = new File(

"C:/W12Assignment/MyNumbers.txt"); /* Default file */

static ArrayList<Double> nums = new ArrayList<Double>();

static boolean exit = false; // Used for an exit flag

// Begin Main Method

public static void main(String[] args) throws FileNotFoundException, IOException {

/*

*

* Variables

*

*/

int menuChoice = 0;

int exitNum = 1;

int lowRange = 1;

int upRange = 3;

// Display welcome message

System.out.println("Welcome to My Statistics Calculator");

/**

*

* Call menu options list method (below)

*

*/

enterFileName();

do {

/**

*

* Handle menu selections. Validate and check for errors. Begin an

*

* inner do loop here (below this comment block)

*

*/

do {

System.out.println("Please select from the following menu of options:");

System.out.print("1. Enter Data " + "2. Read Data " + "3. Exit " + "->: ");

/**

*

* Begin try block here (below this comment block). This will be

*

* used to validate the user's entry is an integer AND if it is

*

* within range.

*

*/

try {

// Begin 2nd inner do loop here

do {

menuChoice = sc.nextInt();

chkErr.setRange(menuChoice, lowRange, upRange);

System.out.println(); // Clears the buffer

/**

*

* End 2nd inner do loop here (below this comment block)

*

* with while that looks for a boolean value from the

*

* check errors subclass method

*

*/

} while (!chkErr.getRange());

} catch (InputMismatchException IME) {

System.err.println("Exception. You must enter a number. Please try again.");

sc.nextLine(); // Clears the buffer

}

} while (!chkErr.getRange()); // End inner do loop

/* Handle menu entries */

switch (menuChoice) {

case 1:

// Call to write data to a file method here

writeData();

System.out.print("Would you like to read the see the results? ->: ");

// Begin do loop

do {

ans = sc.next();

if (ans.equalsIgnoreCase("Y")) {

readData();

} else if (ans.equalsIgnoreCase("N")) {

break;

}

chkErr.setYesNo(ans);

} while (!chkErr.getYesNo()); // End inner loop

break;

case 2:

readData();

break;

case 3:

/**

*

* Call to exit method here and send it the exit number. This

*

* should be a 1 as initialized above that will exit the program

*

* cleanly. See Exit method below

*

*/

Exit(exitNum);

break;

default:

/**

*

* First, set exit number to 2 here. Then, Call to exit method

*

* here and send it the exit number. This should be a 2 as set

*

* just above. This will exit the program with a fault. See Exit

*

* method below

*

*/

exitNum = 2;

Exit(exitNum);

break;

}

do { // Begin another do loop here

System.out.print("Would you like to run the program again? ->: ");

ans = sc.next();

if (ans.equalsIgnoreCase("Y")) {

exit = false;

} else {

exit = true;

}

// Call to check input

chkErr.setYesNo(ans,

exit); /*

*

* Send answer to CheckErrors subclass for eval

*

*/

} while (!chkErr.getYesNo()); // End inner loop

} while (ans.equalsIgnoreCase("Y"));

} // End Main Method

/**

*

* Method readData: Used to call to subclass ReadData to read a files

*

* contents Find minimum, maximum, average, and standard deviation of

*

* numbers in file

*

*

*

* @throws FileNotFoundException

*

*/

public static void readData() throws FileNotFoundException {

if (file.length() != 0) { // Check file length is not = 0

rData.setData(FILE_DIR, file);

try (Scanner input = new Scanner(file)) {

System.out.println("The numbers in this file are:");

while (input.hasNextLine()) {

String line = input.nextLine();

System.out.println(line);

}

}

System.out.printf("The average of the numbers in file name is: %.4f ", rData.getAvg());

System.out.printf("The smallest number in the file is: %.4f ", rData.getMin());

System.out.printf("The largest number in the file is: %.4f ", rData.getMax());

System.out.printf("The standard deviation for the numbers in this file is: %.4f ", rData.getStdDev());

} else {

System.out.print("The file contains no data. Enter data? ->: ");

do {

ans = sc.next();

if (ans.equalsIgnoreCase("Y")) {

// Call Write data method

writeData();

System.out.print("Would you like to read the see the results? ->: ");

do {

ans = sc.next();

if (ans.equalsIgnoreCase("Y")) {

// Call read data method

readData();

} else if (ans.equalsIgnoreCase("N")) {

break;

}

chkErr.setYesNo(ans);

} while (!chkErr.getYesNo()); // End inner loop

} else if (ans.equalsIgnoreCase("N")) {

break;

}

chkErr.setYesNo(ans);

} while (!chkErr.getYesNo()); // End inner loop

}

}

/**

*

* Method Exit: Used to exit program cleanly

*

*

*

* @param num

*

*/

public static void Exit(int num) {

if (num == 1) {

// Tell user goodbye

System.exit(0);

} else {

// Tell user there was a System Error Exiting Program"

System.exit(1);

}

}

/**

*

* Method writeData: Used to write data to file

*

*

*

* @throws FileNotFoundException

*

*/

private static void writeData() throws FileNotFoundException {

int high; /* Used for number of elements to enter */

double num; /* variable for entered number */

boolean flag = false; /* Used for outer do loop */

boolean iFlag; /* Used for inner do loop */

do { // Begin do loop

System.out.print("How many numbers would you like to send to the file? ->: ");

try { // Begin try block

high = sc.nextInt();

do { // Begin inner do loop

for (int i = 1; i <= high; i++) {

try {

System.out.printf("Enter number %d -> ", i);

num = sc.nextDouble();

nums.add(num); // Add user entry to arraylist

} catch (InputMismatchException IME) { // Catch block to

// catch errors

iFlag = false; // If error, set inner flag variable

sc.nextLine(); /* Clear buffer */

i -= 1; // Reset counter variable

System.err.println("Entry Error: Please enter a number.");

}

}

iFlag = true; // Reset value if errored once so it can

// continue on a proper entry after retry

} while (!iFlag); // Condition to continue loop

// Write data to file

wData.setData(FILE_DIR, file, nums, nums.size());

flag = true; // reset outer flag value

} catch (InputMismatchException IME) {

/* set outer flag value to false */

sc.nextLine(); /* Clear buffer */

System.err.println("Entry Error: Please enter a number.");

}

} while (!flag); // While inner flag variable is true

//nums.clear(); // clears the arraylist of all values.

}

/**

*

* Method enterFileName: Used to create file and directory

*

*

*

* @throws IOException

*

*/

private static void enterFileName() throws IOException {

String fileName = "";

System.out.print("Enter the name of your text file (e.g. MyNumbers) "

+ "The file extension will be added after entry. ->: ");

fileName = sc.next();

// File name with extension .txt

String fileNameWithExt = fileName.concat(".txt");

// Ceate file

File file_Name = new File(FILE_DIR + "/" + fileNameWithExt);

/* Create directory */

if (!FILE_DIR.exists()) {

FILE_DIR.mkdirs();

System.out.printf(" The directory does not exist. Creating directory..."

+ " Directory created at this location ->: " + "%s ", FILE_DIR.getAbsolutePath());

} else {

System.out.printf(" The directory exists at this location ->: " + "%s ", FILE_DIR.getAbsolutePath());

}

/* Create file */

file = file_Name;

if (!file.exists()) {

System.out.println("The file does not exist. Creating file...");

file.createNewFile();

System.out.printf(" File created at this location ->: " + "%s ", file.getAbsolutePath());

} else {

System.out.printf("The file exists at this location ->: " + "%s ", file.getAbsolutePath());

}

}

} // End Class W12Assignment

Output

Welcome to My Statistics Calculator
Enter the name of your text file (e.g. MyNumbers)
The file extension will be added after entry.
->: MyNumbers

The directory does not exist.
Creating directory...
Directory created at this location ->: C:W12Assignment

The file does not exist.
Creating file...

File created at this location ->: C:W12AssignmentMyNumbers.txt

Please select from the following menu of options:
1. Enter Data
2. Read Data
3. Exit
->: 2

The file contains no data.
Enter data? ->: n
Would you like to run the program again? ->: y

Please select from the following menu of options:
1. Enter Data
2. Read Data
3. Exit
->: 1

How many numbers would you like to send to the file? ->: 6
Enter number 1 -> 89.635
Enter number 2 -> 100.3069
Enter number 3 -> 101.0009
Enter number 4 -> 95.365
Enter number 5 -> 99.3644
Enter number 6 -> 90.00049
Would you like to read the see the results? ->: y
The numbers in this file are:
89.6350
100.3069
101.0009
95.3650
99.3644
90.0005
The average of the numbers in file name is: 95.9455
The smallest number in the file is: 89.6350
The largest number in the file is: 101.0009
The standard deviation for the numbers in this file is: 4.6863
Would you like to run the program again? ->: y

Please select from the following menu of options:
1. Enter Data
2. Read Data
3. Exit
->: 2

The numbers in this file are:
89.6350
100.3069
101.0009
95.3650
99.3644
90.0005
The average of the numbers in file name is: 95.9455
The smallest number in the file is: 89.6350
The largest number in the file is: 101.0009
The standard deviation for the numbers in this file is: 4.6863
Would you like to run the program again? ->: y

Please select from the following menu of options:
1. Enter Data
2. Read Data
3. Exit
->: 1

How many numbers would you like to send to the file? ->: 3
Enter number 1 -> 789.36
Enter number 2 -> 790.46

Enter number 3 -> 698.99
Would you like to read the see the results? ->: y
The numbers in this file are:
89.6350
100.3069
101.0009
95.3650
99.3644
90.0005
789.3600
790.4600
698.9900
The average of the numbers in file name is: 317.1647
The smallest number in the file is: 89.6350
The largest number in the file is: 790.4600
The standard deviation for the numbers in this file is: 313.8519
Would you like to run the program again? ->: n
Thank you for using the program!
Good Bye!