Write a program that has a class called Student. The private fields in the class
ID: 3679533 • Letter: W
Question
Write a program that has a class called Student. The private fields in the class are two Strings that hold first name and last name, and a double that holds a GPA. Write a constructor that accepts the first and last names, but NOT the GPA.
Write a set and get method for each of the three fields. Using if( ) statements exactly like you would do in C (the syntax is identical) restrict the setGPA( ) method to only accept values between 0.0 and 4.0. For example, on the top end you might do
if(value>4.0){
value=4.0;
}
In the main( ) method, create two instances of the student class using the constructor you wrote, and set their GPA's using the setGPA( ) method.
Explanation / Answer
Please find below the classes implemented as per your requirement.
Student.java
public class Student {
private String firstName;
private String lastName;
private double GPA;
public Student(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
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;
}
public double getGPA() {
return GPA;
}
public void setGPA(double gPA) {
if(gPA > 4.0){
gPA = 4.0;
} else if(gPA < 0.0){
gPA = 0.0;
}
this.GPA = gPA;
}
}
Main.java
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu1 = new Student("FirstName1", "LastName1");
Student stu2 = new Student("FirstName2", "LastName2");
stu1.setGPA(2.0);
stu2.setGPA(3.0);
System.out.println("Obj1 Stu1 GPA - "+stu1.getGPA()+" :: Obj2 Stu2 GPA - "+stu2.getGPA());
System.out.println("Obj1 Stu1 FirstName - "+stu1.getFirstName()+" :: Obj1 Stu1 LastName - "+stu1.getLastName());
System.out.println("Obj2 Stu2 FirstName - "+stu2.getFirstName()+" :: Obj2 Stu2 LastName - "+stu2.getLastName());
}
}
Steps for Execution:
Open cmd prompt and go to the path where these java files have been saved.
> javac Main.java
> java Main
Output1:
if you set GPA as 2.0 in st1 obj and 3.0 in stu2 object then output like below
Obj1 Stu1 GPA - 1.0 :: Obj2 Stu2 GPA - 3.0
Obj1 Stu1 FirstName - FirstName1 :: Obj1 Stu1 LastName - LastName1
Obj2 Stu2 FirstName - FirstName2 :: Obj2 Stu2 LastName - LastName2
Output2:
if you set GPA as -1.0 in st1 obj and 5.0 in stu2 object then output like below
Obj1 Stu1 GPA - 0.0 :: Obj2 Stu2 GPA - 4.0
Obj1 Stu1 FirstName - FirstName1 :: Obj1 Stu1 LastName - LastName1
Obj2 Stu2 FirstName - FirstName2 :: Obj2 Stu2 LastName - LastName2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.