Question by Joel C: Java coding question using Constructor?
I am taking a an online Java Programming class using “Java Programming” by Joyce Farrell. I am trying to figure out the coding on an exercise from Chapter 3 and the instructor is not responding so I wanted to see if someone here had the answer.
We just learned constructors and we are supposed to be writing a class called student with fields for ID Number, number of credit hours, number of points earned, and grade point average (GPA). I can figure out how to create the methods to assign values to all the fields, but GPA needs to equal points earned divided by credit hours. So far, GPA has always returned a double “0.0” or a “NaN” and I have tried using the get/set methods and everything I can think of. I am not looking for a specific code as much as guidance as to how to go about coding it since I have tried everything but still want to figure it out myself.
Here is the question as written in the book:
“Create a class named Student. A Student 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.”
Thank you for your help!
Answer by Frank
Based on what I’ve seen other students do, I’m guessing that in the constructor you are calculating the GPA and storing it in a field. That is incorrect.
Define a method to calculate the GPA on the fly. It does not store the GPA in a field for use later. It calculates and returns the GPA using the current field values for credit hours and points. This method does not get called in the constructor. It gets called later, after the other values have been set.
What do you think? Answer below!