Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

3. [10 points] Write a Student class with the fields name, major, and gpa. The f

ID: 3914902 • Letter: 3

Question

3. [10 points] Write a Student class with the fields name, major, and gpa. The fields name and major should be of type String, and gpa should be of type double. In addition to getters and setters for all three fields, you should also write equals and tostring methods. For the purposes of this assignment, equals) returns true if and only if the parameter is an instance of a Student, with identical name,major, and gpa fields. The setter for the gpa field should include validation, throwing an exception if an attempt is made to set it less than zero or greater than 4.0.

Explanation / Answer

Given below is the code for the question.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you

public class Student {
private String name;
private String major;
private double gpa;

public Student() {
name = "";
major = "";
gpa = 0;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getMajor() {
return major;
}

public void setMajor(String major) {
this.major = major;
}

public double getGpa() {
return gpa;
}

public void setGpa(double gpa) {

if(gpa < 0 || gpa > 4.0)
throw new IllegalArgumentException("Invalid gpa " + gpa);
this.gpa = gpa;
}


@Override
public boolean equals(Object obj) {
if(obj instanceof Student){
Student s2 = (Student)obj;

if(name.equals(s2.name) && major.equals(s2.major) && gpa == s2.gpa)
return true;
}

return false; //if parameter not a student or instance variables don't match

}

@Override
public String toString() {
return String.format("Name: %s Major: %s GPA: %.2f ", name, major, gpa);
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote