Write a program ComputeStats.java that reads two files and computes min, max, me
ID: 3776563 • Letter: W
Question
Write a program ComputeStats.java that reads two files and computes min, max, mean, and standard deviation of student scores. The program reads two files scores.txt and majors.txt. The file scores.txt contains lines of data. In each line, the first element is a 10-digit student ID, the second element is major code, and the remaining elements are scores obtained in various courses. These elements are separated by space. Read each line in scores.txt, store the values in an array or ArrayList, and compute minimum score, maximum score, mean score, and standard deviation for each student.
Explanation / Answer
//Program
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
class Student
{
String student_ID,major_code;
int Scores[];
public Student(String id, String major, int[]scores)
{
this.student_ID=id;
this.major_code=major;
this.Scores=scores;
}
public String getID()
{
return student_ID;
}
public String getMajor()
{
return major_code;
}
public int getMinScore()
{
int min=Scores[0];
for(int i=1;i<Scores.length;i++)
{
if(Scores[i]<min)
{
min=Scores[i];
}
}
return min;
}
public int getMaxScore()
{
int max=Scores[0];
for(int i=1;i<Scores.length;i++)
{
if(Scores[i]>max)
{
max=Scores[i];
}
}
return max;
}
public double getMeanScore()
{
double total=0;
for(int i=0;i<Scores.length;i++)
{
total+=Scores[i];
}
return total/Scores.length;
}
public double getStdDev()
{
double mean=getMeanScore();
double sum=0;
for(int i=0;i<Scores.length;i++)
{
sum+=Math.pow((Scores[i]-mean),2);
}
return Math.sqrt(sum/Scores.length) ;
}
}
public class ComputeStats {
public static void main(String[] args) throws FileNotFoundException {
ArrayList <Student> students =new ArrayList<>();
int n=0;
Scanner infile=new Scanner(new File("scores.txt"));
while(infile.hasNextLine())
{
String words[]=infile.nextLine().split(" ");
String id=words[0];
String major=words[1];
int scores[]=new int[words.length-2];
for(int i=3;i<words.length;i++)
{
scores[i-3]=Integer.parseInt(words[i]);
}
students.add(new Student(id,major,scores));
}
for(int i=0;i<students.size();i++)
{
System.out.println("Student "+(i+1)+" id: "+students.get(i).getID());
System.out.println("Major: "+students.get(i).getMajor());
System.out.println("Minimum Score: "+students.get(i).getMinScore());
System.out.println("Maximum Score: "+students.get(i).getMaxScore());
System.out.println("Mean Score: "+students.get(i).getMeanScore());
System.out.println("Standard deviation: "+students.get(i).getStdDev()+" ");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.