简体   繁体   中英

How to call a class of instance variables through a method of another class

I am doing a project for school that requires me to build a grade system for a school I am struggling to understand why when I have a class of public variables they are not allowed to be called in the method of another class. Can someone give an example or explain how this could work?

public void AddEngGrade(Grades obj)
{
Scanner sc1 = new Scanner(System.in);


System.out.println("Which Grade would you like to enter");
System.out.println("");
System.out.println("Major");
System.out.println("Minor");
System.out.println("Other");
System.out.println("");

String gr = sc1.nextLine();

if(gr.equals("Major"))
{
  System.out.print("Please enter the grade here - ");
  obj.EngMajor = sc1.nextInt();
  obj.EngMajPoints += obj.EngMajor;
  obj.EngMajorTot++;
  obj.EngMajAvg = (obj.EngMajPoints/2)*(.6);
}

The class with the variables is as follows

import java.util.*;
public class Grades
{
public int EngMajor = 0;
public int EngMinor = 0;
public int EngOther = 0;
public int EngMajorTot = 0;
public int EngMinorTot = 0;
public int EngOtherTot = 0;
public double EngMajAvg = 0;
public double EngMinAvg = 0;
public double EngOtAvg = 0;
public int EngMajPoints = 0;
public int EngMinPoints = 0;
public int EngOtPoints = 0;
}

I think you approaching the design of your classes the wrong way. As this is a homework assignment, I don't want to provide a solution. The Grade class should not care if it is a major or a minor. A grade is something a student gets for taking a course. Whether that course counts as a major or minor is an attribute of the student's curriculum. A course does not have a major/minor attribute.

To compute the average, sum the points, etc for the major, you want to iterate over the grades from the courses in the student's curriculum that are part of the major. A student class could have a method called computeMajorGPA() or perhaps computeGPA(some enum).

I recommend that you avoid having classes that are plural. I think classes that represent singular objects is better design and multiple objects should be handled by a collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM