Question

In: Computer Science

In java Write a program called FileProcessor.java that reads the file numbers.txt, and: Calculate the total...

In java

Write a program called FileProcessor.java that reads the file numbers.txt, and:

Calculate the total number of numbers in the file, Calculate the sum of all the numbers in the file, Calculate the average of all the numbers in the file, Find the smallest value of all the numbers in the file, Find the largest value of all the numbers in the file, Calculate the standard deviation of all the numbers in the file

Solutions

Expert Solution

Hi,

Please find the code below:

Note:

1. We are assuming that the number.txt file will only consist of number(or white spaces).

2. If in case program won't work, please place a comment. I will try to get the answer as soon as possible.

====================Code====================

import java.io.File; // Import the File class

import java.io.FileNotFoundException; // Import this class to handle errors

import java.util.Arrays;

import java.util.Scanner; // Import the Scanner class to read text files

public class FileProcessor {

//Wrote this method separately to calculate the standard deviation

//This method accept double array to calculate the standard deviation

//It will return the calculated standard deviation

public static double standardDeviation(double numArray[])

{

double sum = 0.0, standardDeviation = 0.0;

int length = numArray.length;

for(double num : numArray) {

sum += num;

}

double mean = sum/length;

for(double num: numArray) {

standardDeviation += Math.pow(num - mean, 2);

}

return Math.sqrt(standardDeviation/length);

}

//Main method

public static void main(String[] args) {

//Declaring variables which can be used

int[] arrayOfNumbers;

String data;

double totalCount;

double averageOfNumbers;

try {

//Reading number.text file which is place inside my project directory

//Writing this inside try block because it may throw an exception if file not found

File myObj = new File("number.txt");

Scanner myReader = new Scanner(myObj);

totalCount=0;

averageOfNumbers=0;

//Reading line by line (We are assuming the file only consists of numbers)

while (myReader.hasNextLine()) {

data = myReader.nextLine();

//replacing all the white spaces

data=data.replaceAll("\\s", "");

//Count the total number of numbers in file

System.out.println("Total number of numbers ="+data.length());

arrayOfNumbers=new int[data.length()];

/*Splitting the string to convert it into string array,

* this will help us to parse it into integer array in next step.

*

*/

String[] ary = data.split("");

//Assigning all the string array data to integer array by parsing it.

//It will be easier to work on int array of number than string array pf numbers

for(int i=0;i<arrayOfNumbers.length;i++) {

arrayOfNumbers[i]=Integer.parseInt(ary[i]);

}

//Calculating the sum of all numbers

for(int i=0;i<arrayOfNumbers.length;i++) {

totalCount=totalCount+arrayOfNumbers[i];

}

System.out.println("Total sum of numbers= "+totalCount);

//Calculating the average of all the numbers

averageOfNumbers=totalCount/data.length();

System.out.println("Average of all the numbre are="+averageOfNumbers);

//Sorting int array to get the smallest number and largest number in the file

Arrays.sort(arrayOfNumbers);

System.out.println("Smallest number= "+arrayOfNumbers[0]);

System.out.println("Largest value in numbers is= "+arrayOfNumbers[data.length()-1]);

//Converting the int array of number to double so that we can feed this double array to standard deviation function

double[] arrayOfNumbersInDoubleToCalculateStandardDeviation = new double[arrayOfNumbers.length];

for(int i=0; i<arrayOfNumbers.length; i++) {

arrayOfNumbersInDoubleToCalculateStandardDeviation[i] = arrayOfNumbers[i];

}

System.out.println("Standard deviation is=" +standardDeviation(arrayOfNumbersInDoubleToCalculateStandardDeviation));

}

myReader.close();

} catch (FileNotFoundException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}

}

}

======================Output================

===================If you find this helpful then please consider upvoting me====Thanks=====


Related Solutions

Write a program that reads a file called document.txt which is a text file containing an...
Write a program that reads a file called document.txt which is a text file containing an excerpt from a novel. Your program should print out every word in the file that contains a capital letter on a new line to the stdout. For example: assuming document.txt contains the text C++
Write a program in Java that reads a file containing data about the changing popularity of...
Write a program in Java that reads a file containing data about the changing popularity of various baby names over time and displays the data about a particular name. Each line of the file stores a name followed by integers representing the name’s popularity in each decade: 1900, 1910, 1920, and so on. The rankings range from 1 (most popular) to 1000 (least popular), or 0 for a name that was less popular than the 1000th name. A sample file...
Using Java Project 2: Deduplication Write a program that reads a file of numbers of type...
Using Java Project 2: Deduplication Write a program that reads a file of numbers of type int and outputs all of those numbers to another file, but without any duplicate numbers. You should assume that the input file is sorted from smallest to largest with one number on each line. After the program is run, the output file should contain all numbers that are in the original file, but no number should appear more than once. The numbers in the...
Write a Java program that reads a list of 30 fruits from the file “fruits.txt”, inserts...
Write a Java program that reads a list of 30 fruits from the file “fruits.txt”, inserts them into a string array, and sorts the array in alphabetical order. String objects can be compared using relational operators such as <, >, or ==. For example, “abc” > “abd” is false, but “abc” < “abd” is true. Sample output: Before Sorting: Cherry, Honeydew, Cranberry, Lemon, Orange, Persimmon, Watermelon, Kiwifruit, Lime, Pomegranate, Jujube, Pineapple, Durian, Plum, Banana, Coconut, Apple, Tomato, Raisin, Mandarine, Blackberry,...
Write a JAVA program that reads a text file into RAM efficiently, takes a regular expression...
Write a JAVA program that reads a text file into RAM efficiently, takes a regular expression from the user, and then prints every line that matches the RE.
Write a Java program (single file/class) whose filename must be Numbers.java. The program reads a list...
Write a Java program (single file/class) whose filename must be Numbers.java. The program reads a list of integers from use input and has the following methods: 1. min - Finds the smallest integer in the list. 2. max- Finds the largest integer in the list. 3. average - Computes the average of all the numbers. 4. main - method prompts the user for the inputs and ends when the user enter Q or q and then neatly outputs the entire...
C++ Write a program that prompts for a file name and then reads the file to...
C++ Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid. Display the line number the error occurred on. These are a few of the...
Java Code using Queue Write a program that opens a text file and reads its contents...
Java Code using Queue Write a program that opens a text file and reads its contents into a queue of characters, it should read character by character (including space/line change) and enqueue characters into a queue one by one. Dequeue characters, change their cases (upper case to lower case, lower case to upper case) and save them into a new text file (all the chars are in the same order as the original file, but with different upper/lower case) use...
Java Code using Stack Write a program that opens a text file and reads its contents...
Java Code using Stack Write a program that opens a text file and reads its contents into a stack of characters, it should read character by character (including space/line change) and push into stack one by one. The program should then pop the characters from the stack and save them in a second text file. The order of the characters saved in the second file should be the reverse of their order in the first file. Ex input file: Good...
2. Write a Java program that reads a series of input lines from given file “name.txt”,...
2. Write a Java program that reads a series of input lines from given file “name.txt”, and sorts them into alphabetical order, ignoring the case of words. The program should use the merge sort algorithm so that it efficiently sorts a large file. Contents of names.text Slater, KendallLavery, RyanChandler, Arabella "Babe"Chandler, StuartKane, EricaChandler, Adam JrSlater, ZachMontgomery, JacksonChandler, KrystalMartin, JamesMontgomery, BiancaCortlandt, PalmerDevane, AidanMadden, JoshHayward, DavidLavery,k JonathanSmythe, GreenleeCortlandt, OpalMcDermott, AnnieHenry, DiGrey, MariaEnglish, BrookeKeefer, JuliaMartin, JosephMontgomery, LilyDillon, AmandaColby, LizaStone, Mary FrancesChandler, ColbyFrye, DerekMontgomery,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT