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

I have a .txt file with 10 test scores. For example: 10 1 2 3 4 5 6 7 8 9 10, wh

ID: 644654 • Letter: I

Question

I have a .txt file with 10 test scores. For example: 10 1 2 3 4 5 6 7 8 9 10, where the first 10 is the number of scores and the others are the actual acores. I need to create a simple java program that imports the .txt file from the user's input ( e.g. with a scanner), reads the above file/data into an array, sorts and prints the scores from smallest to largest, and calculate and print: smallest score, median, highest score, average, SD, and number of a's, b's, c's, d's, and f's. I have the basic code to import the file and throw an exception if the file doesn't exist but it won't print any of the text. What is bothering me is this should work for no matter what file and data. Can somebody help me with the example I just made up?

Explanation / Answer

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;


public class scores {

private static Scanner inFile;

public static void main(String[] args) throws FileNotFoundException {
      
      
       String fileName="score.txt";
       ArrayList<Integer> scores = new ArrayList<>();
      
       inFile = new Scanner(new File(fileName));
  
       int no = inFile.nextInt();
       int sum = 0;
       float median, avg, sd=0;

for(int i=0; i<no; i++)
{
   int d = inFile.nextInt();
   sum+=d;
   scores.add(d);
}

avg = (float) (sum/no);

for(int i=0; i<no; i++)
{
   sd += (scores.get(i) - avg)*(scores.get(i) - avg);
}
sd = (float) Math.sqrt(sd / (no-1));




//sort ascending
Collections.sort(scores);

System.out.println("Array sorted in ascending order: ");
System.out.println(scores.toString());

System.out.println(" Smallest data: "+scores.get(0));
System.out.println("Largest data: "+scores.get(scores.size() - 1));

if(no%2 == 0)
   median = (scores.get((no-1)/2) + scores.get(((no-1)/2) + 1)) / 2;
else
   median = scores.get((no/2));

System.out.println("Media data: "+median);
System.out.println("Average data: "+avg);
System.out.println("SD : "+sd);

int grade[] = new int[5];
for(int i=0; i<no; i++)
{
   if(scores.get(i) >= 90)
       grade[0]++;
   else if(scores.get(i) >= 80)
       grade[1]++;
   else if(scores.get(i) >= 70)
       grade[2]++;
   else if(scores.get(i) >= 60)
       grade[3]++;
   else
       grade[4]++;
}
System.out.println(" Grade:--");
System.out.println("a : "+grade[0]);
System.out.println("b : "+grade[1]);
System.out.println("c : "+grade[2]);
System.out.println("d : "+grade[3]);
System.out.println("e : "+grade[4]);

   }
}

---------------------------------------------------------------------------------------------------------------------------------------
score.txt

10 51 12 43 24 25 86 17 85 29 10