Array of Objects
Completed
Create Student(String name, int mark). Read n students into an array and print the top student and the class average (1 decimal).
Input
n, then n lines name mark.
Output
Two lines: top: NAME (MARK), average: X.
Example
Input
3 ann 72 bob 91 cy 85
Output
top: bob (91) average: 82.7
Editor
Java
Hints
new Student[n] creates n empty slots (null); fill each one with new Student(...).
Solution explanation
An array of objects holds references; each element must be created separately.
Show solution
import java.util.Scanner;
class Student {
final String name;
final int mark;
Student(String name, int mark) {
this.name = name;
this.mark = mark;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Student[] students = new Student[n];
int total = 0;
for (int i = 0; i < n; i++) {
students[i] = new Student(sc.next(), sc.nextInt());
total += students[i].mark;
}
Student top = students[0];
for (Student s : students) {
if (s.mark > top.mark) {
top = s;
}
}
System.out.println("top: " + top.name + " (" + top.mark + ")");
System.out.printf("average: %.1f%n", (double) total / n);
}
}