Project: Class Results
Read n students. Each line has a name followed by exactly three marks. For each student, work out the average (1 decimal) and a grade (A: 90+, B: 75+, C: 50+, F: below 50). Print the students sorted by average from highest to lowest (ties: alphabetical by name) as <name> <average> <grade>. Then print Class average: <avg of all averages, 1 decimal>.
Input
First n, then n lines: name m1 m2 m3.
Output
As described above.
Example
Input
3 Asha 95 88 92 Ravi 70 65 80 Meera 45 52 38
Output
Asha 91.7 A Ravi 71.7 C Meera 45.0 F Class average: 69.4
Hints
Divide the sum by 3.0 to keep the decimals.
Double.compare(b.avg, a.avg) sorts high to low.
printf("%s %.1f %c%n", ...) prints a String, a 1-decimal number and a char.
Solution explanation
A small class holds each result, a comparator sorts them, and a stream works out the class average.
Show solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Result {
String name;
double avg;
Result(String name, double avg) {
this.name = name;
this.avg = avg;
}
char grade() {
if (avg >= 90) return 'A';
if (avg >= 75) return 'B';
if (avg >= 50) return 'C';
return 'F';
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Result> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
String name = sc.next();
int sum = sc.nextInt() + sc.nextInt() + sc.nextInt();
list.add(new Result(name, sum / 3.0));
}
list.sort((a, b) -> a.avg != b.avg ? Double.compare(b.avg, a.avg) : a.name.compareTo(b.name));
for (Result r : list) {
System.out.printf("%s %.1f %c%n", r.name, r.avg, r.grade());
}
double classAvg = list.stream().mapToDouble(r -> r.avg).average().getAsDouble();
System.out.printf("Class average: %.1f%n", classAvg);
}
}You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module