Question
Hi below is my java code i have to just make a little changes. my code is running accurately....the only problem i am facing is
Hi below is my java code i have to just make a little changes. my code is running accurately....the only problem i am facing is that when I am entering data again instead of getting only new data it is also giving me the old data that I entered. how can I fix that even entering data second time it will gice me only my new data that i entered adn not the old one. please look at the ouput to understand better.
Main.java
//Imports import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner;
//Begin Class public class Sample{
static Scanner sc = new Scanner(System.in);
static ReadData rData = new ReadData();
static WriteData wData = new WriteData();
static ValidateEntries VE = new ValidateEntries();
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
static boolean exit = false; // Used for an exit flag
// Begin Main Method
public static void main(String[] args) throws FileNotFoundException, IOException {
int menuChoice = 0;
int exitNum = 1;
int lowRange = 1;
int upRange = 3;
// Display welcome message
System.out.println("Welcome to My Statistics Calculator");
enterFileName();
do {
do {
System.out.println("Please select from the following menu of options:");
System.out.print("1. Enter Data " + "2. Read Data " + "3. Exit " + "->: ");
try {
// Begin 2nd inner do loop here
do {
menuChoice = sc.nextInt();
VE.setRange(menuChoice, lowRange, upRange);
System.out.println(); // Clears the buffer
} while (!VE.getRange());
} catch (InputMismatchException IME) {
System.err.println("Exception. You must enter a number. Please try again.");
sc.nextLine(); // Clears the buffer
}
} while (!VE.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;
}
VE.setYesNo(ans);
} while (!VE.getYesNo()); // End inner loop
break;
case 2:
readData();
break;
case 3:
Exit(exitNum);
break;
default:
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
VE.setYesNo(ans,
exit); /*
*
* Send answer to CheckErrors subclass for eval
*
*/
} while (!VE.getYesNo()); // End inner loop
} while (ans.equalsIgnoreCase("Y"));
} // End Main Method
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;
}
VE.setYesNo(ans);
} while (!VE.getYesNo()); // End inner loop
} else if (ans.equalsIgnoreCase("N")) {
break;
}
VE.setYesNo(ans);
} while (!VE.getYesNo()); // End inner loop
}
}
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);
}
}
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.
}
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());
}
Write data:
//Imports import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner;
//Begin Subclass WriteData public class WriteData {
// Instance variables
private File fFile; // variable for file
private File fDir; // variable for file directory
public void setData(File fileDir, File file, ArrayList
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
Read data
//Imports import java.io.File; import java.io.FileNotFoundException; import static java.lang.Math.pow; import static java.lang.Math.sqrt; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner;
//Begin Subclass ReadData public 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
ArrayList
// 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
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);
}
private void setAvg(ArrayList
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();
}
private void setMinMax(ArrayList
max = Collections.max(nums); // Finds the highest number in the set
min = Collections.min(nums); // Finds the lowest number in the set
}
private void setStdDev(ArrayList
/* Reset variables */
avg_copy = 0;
avgSqrdDiff = 0;
stdDev = 0;
/* reset array */
sdNums.clear();
/* Get Mean/Average of numbers */
avg_copy = getAvg();
for (double i : nums) {
i -= avg_copy;
sdNums.add(pow(i, 2));
}
for (double x : sdNums) {
avgSqrdDiff += x;
}
avgSqrdDiff /= sdNums.size();
stdDev = sqrt(avgSqrdDiff);
}
public double getAvg() {
return avg;
}
public double getMax() {
return max;
}
public double getMin() {
return min;
}
public double getStdDev() {
return stdDev;
}
} //End Subclass ReadData
Validate Entries:
public class ValidateEntries {
private boolean flag;
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;
}
} 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;
}
}
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;
}
}
public boolean getYesNo() {
return flag;
} public boolean getRange() {
return flag;
}
} //End Subclass ValidateEntries
Here is the output that it should be and things that should be included:
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:\W12Assignment\MyNumbers.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!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started