In: Computer Science
Write a class encapsulating the concept of a Student, assuming that a student has the following attributes: last name, first name, id, array of grades. Include a constructor, the accessors and mutators, and method toString. Also code the following methods: one returning the GPA using the array of grades (assuming each grade represents a course grade and all courses have the same number of credit hours) and a method to add a course grade to the array of grades (this means creating a larger array). Write a client class to create 2 student objects and test all your methods.
Student.java
public class Student {
// instance variables
private int id;
private String firstName;
private String lastName;
private double[] grades=new double[10]; // grades
array
private static int courseCount=0; // variable to keep
record of grades array
// default constructor
public Student() {
super();
courseCount=0;
}
// parameterized constructor
public Student(int id, String firstName, String
lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
courseCount=0;
}
// setters and getters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// method to calculate GPA
public double getGPA() {
double total = 0;
for(int i=0;i<courseCount;i++)
{
total+=grades[i];
}
return total/courseCount;
}
// method to add course grade into grades array
public void addCourseGrade(double grade) {
grades[courseCount]=grade;
courseCount++;
}
// method to get grades to display
public String displayGrades() {
String gradeString="";
for(int
i=0;i<courseCount;i++)
gradeString=gradeString+" "+grades[i];
return gradeString;
}
@Override
public String toString() {
return "\nStudent:"
+ "\nId: "+id
+"\nFirst Name: "+firstName
+"\nLast Name: "+lastName
+"\nGrades: "+displayGrades();
}
}
StudentClient.java
public class StudentClient {
public static void main(String[] args) {
// create Student object
Student student1=new Student(101,
"Steve", "Rogers");
student1.addCourseGrade(95); // add
course grade
student1.addCourseGrade(82);
student1.addCourseGrade(93);
System.out.println(student1); //
print student details
System.out.println("GPA:
"+student1.getGPA()); // display GPA
Student student2=new
Student(102,"Rabia","Hasan");
student2.addCourseGrade(75);
student2.addCourseGrade(83);
student2.addCourseGrade(74);
System.out.println(student2);
System.out.println("GPA:
"+student2.getGPA());
}
}
Output