CrypticZero CrypticZero - 2 months ago 8
Java Question

How do I pass these variables to calculate a new GPA in my class?

sorry for this very similar question to my last post, but I'm having a slightly different problem to my last question. I have gotten everything to compile and work in my project, but I am not sure how to calculate a new gpa for student1 and student2 in my class by passing a total amount of points and a total amount of classes. My teacher wants us to calculate student1's gpa by passing 40 total points for 7 classes and to calculate student2's gpa by passing 36 total points for 8 classes. Like I said, the rest of my code works, I'm just not sure how to do this yet as I'm still fairly new to coding. The answer is probably pretty simple, but I can't figure it out for the life of me. Here is my code:

public class student
{
private String name;
private int year;
private int age;
private double gpa;
/*
* Default Constructor
*/
public student()
{
name = "John";
year = 2016;
age = 16;
gpa = 4.0;
}
/*
* other constructor
*/
public student(String name, int year, int age, double gpa)
{
this.name = name;
this.year = year;
this.age = age;
this.gpa = gpa;
}
/*
* accessors
*/
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int getYear()
{
return year;
}
public double getGpa()
{
return gpa;
}
/*
* mutators
*/
public void setName(String name)
{
this.name=name;
}
public void setGpa(double gpa)
{
this.gpa=gpa;
}
public void setYear(int year)
{
this.year=year;
}
public void setAge(int age)
{
this.age=age;
}
/*
* calculate GPA
*/
public double calcGpa(double points, int classes)
{
gpa = points / classes;
return gpa;
}
public String toString()
{
return name + year + age + gpa;
}
}



public class studentReal
{
public static void main(String[] args)
{
student student1= new student("Jackie Java", 2018, 16, 4.7);
student student2= new student("John Java", 2019, 15, 3.8);
student student3= new student();
System.out.println(student1.getName() + ", class " + student1.getYear()+ ", " + student1.getAge() + ", " + student1.getGpa());
System.out.println(student2.getName() + ", class " + student2.getYear()+ ", " + student2.getAge() + ", " + student2.getGpa());
System.out.println(student3.getName() + ", class " + student3.getYear()+ ", " + student3.getAge() + ", " + student3.getGpa());
}
}

Answer

In your studentReal class, inside the main method, use the calcGpa method you created within the Student class, for each student. The method, just like the variables, belongs to that student.

For example:

    student1.calcGpa(40, 7);