Jason Osborn Jason Osborn - 2 months ago 6
Java Question

how do you multiple variables in multiple methods?


I have a class (MarkCollection) that basically gets the marks from a user in one method (getMarks), then it gets the average of those marks in another method (getAverage) and lastly it needs to get the grade of the average mark in the 3rd method (getGrades).


Everything works perfectly until i get to the getGrades method. What i need to know is how do i get the 'average' variable (which stores the average of the marks) into the getGrades method. The getGrades method needs to take the 'average' variable and put it through an IF statement to get whatever grade the student will get based on the average.

In short, how do i get the variable 'average' (with the same value stored inside of it as in the getAverage method) into the getGrades method to work out the average correctly?

class MarkCollection extends Main {

Scanner input = new Scanner(System.in);
int length = 3;

int[] marks = new int[length];

public void getMarks(){


for (int counter = 0; counter < length; counter++) {
System.out.println("enter mark number " + (counter + 1));
marks[counter] = Integer.parseInt(input.next());
}

input.close();
}

public void getAverage(){

int sum = 0;

for(int i=0; i < marks.length ; i++)
sum = sum + marks[i];

//calculate average value
double average = sum / marks.length;

System.out.println("Students Mark average is : " + average);

}



Everything works fine until this method. The program doesnt recognize the 'average' variable. How do i get this method to recognize the average variable as it does in the previous method, with the same value stored inside of it.


public void getGrade(){


double grade;

if (average >= 90) {
grade = 1.1;
} else if (average >= 70 ) {
grade = 2.1;
} else if (average >= 50 ) {
grade = 2.2;
} else if (average >= 70 ) {
grade = 2.1;
} else if (average < 50 ) {
grade = 3.0;

System.out.println("The Students Grade is = " + grade);
}
}
}

Answer

Your getGrade() method needs to accept a double as a parameter, and your getAverage() method needs to return the average as a double. Then in your either your getMarks() or main method, you need to call your getGrade() method. It would look something like this.

public void getMarks(){
    ...
    getGrade(getAverage());
} 

public double getAverage(){
    double average = 0;
    ...
    return average
}

public void getGrade(double average){
    ...
}

Here are the official javadocs on passing arguments: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html