Write code that reads the numbers contained in the file and computes the followi
ID: 3861896 • Letter: W
Question
Write code that reads the numbers contained in the file and computes the following:
A total count of the numbers in the file.
The smallest and the second smallest number in the file.
The largest and the second largest number in the file.
The mean (i.e. average) of the numbers in the file.
The standard deviation of the numbers in the file. The standard deviation of a list of numbers is
You may have seen another formula for standard deviation. However for programming the one given here is more useful. The code must also use a single loop
a skeleton of the program is below
import java.io.*;
import java.util.Scanner;
public class BasicStats {
public static void main(String[] args) throws IOException {
File inFile = new File("HW7Data.txt");
Scanner input = new Scanner(inFile);
// Your code here
input.close();
}
}
the program has to also be written in java
Explanation / Answer
import java.io.*;
import java.util.Scanner;
public class BasicStats {
public static void main(String[] args) throws IOException {
File inFile = new File("input.txt");
Scanner input = new Scanner(inFile);
// Your code here
int totalCount = 0, temp;
int smallest = Integer.MAX_VALUE, secondSmallest = Integer.MAX_VALUE;
double mean = 0;
double stdDev = 0;
while(input.hasNextInt()){
temp = input.nextInt();
totalCount++;
mean += temp;
if(temp < smallest){
secondSmallest = smallest;
smallest = temp;
}
else if(temp < secondSmallest){
secondSmallest = temp;
}
}
mean /= totalCount;
input = new Scanner(inFile);
while(input.hasNextInt()){
temp = input.nextInt();
stdDev += (temp - mean) * (temp - mean);
}
stdDev /= (totalCount - 1);
stdDev = Math.sqrt(stdDev);
System.out.println("Total count of numbers: " + totalCount);
System.out.println("Smallest Number: " + smallest);
System.out.println("Second smallest Number: " + secondSmallest);
System.out.println("Mean: " + mean);
System.out.println("Standard deviation: " + stdDev);
input.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.