I wanted to get some feedback here on my solution, because the course I am using is not allowing me to submit any answers.
Objectives:
Write a Java program that:
- Create a grades.txt file with some grades inputted in
- Reads these grades from the file and stores it into an
ArrayList
- After storing all elements into the
ArrayList
return the max, min, and average grade of the list- Return an
Arraylist
without any duplicate grades. All duplicated grades must be removed
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
File file = new File("grades.txt");
PrintWriter output = new PrintWriter(file);
output.println("12.5");
output.println("19.75");
output.println("11.25");
output.println("10");
output.println("15");
output.println("13.25");
output.println("14");
output.println("9");
output.println("10");
output.println("19.75");
output.close();
// Reading from the file //
ArrayList<Double> gradesString = new ArrayList<Double>();
Scanner input = new Scanner(file);
while(input.hasNext())
{
String line = input.nextLine();
gradesString.add(Double.parseDouble(line));
}
double result = 0;
for(Double i : gradesString)
{
result += i;
}
double mean = result / gradesString.size();
LinkedHashSet<Double> hashSet = new LinkedHashSet<>(gradesString);
ArrayList<Double> gradesWithoutDuplicates = new ArrayList<Double>(hashSet);
System.out.println("The grades are: " + gradesString);
System.out.println("The highest grade is: " + Collections.max(gradesString));
System.out.println("The lowest grade is: " + Collections.min(gradesString));
System.out.println("The average is: " + mean);
System.out.println("The grades list without duplicates is: " + gradesWithoutDuplicates);
}
}
Output:
The grades are: [12.5, 19.75, 11.25, 10.0, 15.0, 13.25, 14.0, 9.0, 10.0, 19.75]
The highest grade is: 19.75
The lowest grade is: 9.0
The average is: 13.45
The grades list without duplicates is: [12.5, 19.75, 11.25, 10.0, 15.0, 13.25, 14.0, 9.0]
main
) \$\endgroup\$