LearnFrenzy
Sign in Take a free test

Classes and Objects · Classes and Objects Programs · Question 1

Student report card using a class in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write a Student class with a name and an array of marks, methods for total, percentage and grade, and print a report for three students.

Solution
Main.java
class Student {
    String name;
    int[] marks;

    Student(String name, int... marks) { this.name = name; this.marks = marks; }

    int total() { int t = 0; for (int m : marks) t += m; return t; }
    double percentage() { return total() / (double) marks.length; }
    String grade() {
        double p = percentage();
        return p >= 90 ? "A+" : p >= 75 ? "A" : p >= 60 ? "B" : p >= 40 ? "C" : "F";
    }
}

public class Main {
    public static void main(String[] args) {
        Student[] students = {new Student("Asha", 95, 88, 92), new Student("Ravi", 55, 62, 48), new Student("Meena", 76, 81, 79)};
        for (Student s : students) System.out.printf("%-6s %3d %6.2f%% %s%n", s.name, s.total(), s.percentage(), s.grade());
    }
}

Output Verified by compiling and running

Asha   275  91.67% A+
Ravi   165  55.00% C
Meena  236  78.67% A

Each Student object carries its own data, and its methods compute results from that data – the essence of an object.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links