In: Computer Science
Question 1 - Create a class named Student that has fields for an ID number, number of credit hours earned, and number of points earned. (For example, many schools compute grade point averages based on a scale of 4, so a three-credit-hour class in which a student earns an A is worth 12 points.) Include methods to assign values to all fields. A Student also has a field for grade point average. Include a method to compute the grade point average field by dividing points by credit hours earned. Write methods to display the values in each Student field. Save this class as Student.java.
Hi,
Hope you doing fine. I have coded the above question in java keeping all the conditions in mind. The code is explained clearly using comments that have been highlighted in bold. Note that I have named my file as Student1.java as I already had another file called Student.java. You may name the file as per your convenience. Also, pleae note that the file name and class name must be same. I have written an additional class called Test (Test.java) which contains main() and is used to show the output of Student1 class.
Program:
Student1.java
public class Student1 {
//declaring instance variables
int ID;
int credit_hrs;
int num_of_pts;
//considering gpa in double as it is the
average
double gpa;
//method to set ID
public void setID(int iD) {
ID = iD;
}
//method to set the value of
credit_hrs
public void setCredit_hrs(int credit_hrs) {
this.credit_hrs = credit_hrs;
}
//method to set the value of
num_of_pts
public void setNum_of_pts(int num_of_pts) {
this.num_of_pts = num_of_pts;
}
//method to calculate and set the
gpa
public void calculate_Gpa() {
//gpa is calculated by
dividing the number of pts by the credit hrs earned
this.gpa=(double)num_of_pts/credit_hrs;
}
//method to print value of ID
public void getID() {
System.out.println("ID:
"+ID);
}
//method to print credit_hrs
public void getCredit_hrs() {
System.out.println("Credit hours:
"+credit_hrs);
}
//method to print num_of_pts
public void getNum_of_pts() {
System.out.println("Number of
points earned: "+num_of_pts);
}
//method to print gpa
public void getGpa() {
System.out.println("Grade point
average: "+gpa);
}
}
Program:
Test.java
import java.util.Random;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method
stub
//creating new object for
Student
Student1 s=new Student1();
//setting the values of ID,
credit_hrs and num_of_pts
s.setID(1);
s.setCredit_hrs(3);
s.setNum_of_pts(12);
//calculating
gpa
s.calculate_Gpa();
//displaying all
values
s.getID();
s.getCredit_hrs();
s.getNum_of_pts();
s.getGpa();
}
}
Executable code snippets:
Student1.java
Test.java
Output: