154k views
5 votes
Grade Average Lab Assignment Purpose: The goal of this lab assignment is to learn how to use for loops and if/else commands. Write a program that will calculate a numeric average and a letter grade for a student. The main method creates an object of the Grades class that sends two parameters to the Grade class constructor: a student name and the grades to be averaged.

User Fka
by
8.2k points

1 Answer

5 votes

Answer:

//class to test the Grade class

public class GradeTest{

public static void main(String []args){

//create the grades to be averaged

double [] grades = {23, 45, 67, 12.6};

//create an object of the Grade class and

//pass in the necessary arguments to the constructor

Grade grade = new Grade("John", grades);

//print out the results from the Grade object.

System.out.println("Your name is " + grade.getName());

System.out.println("Your average score is " + grade.getAverage());

System.out.println("Your letter grade is " + grade.getLetterGrade());

}

} //End of the GradeTest class

//The Grade class

class Grade {

//create instance variables

private String name;

private double [] grades;

//constructor for the class

public Grade(String name, double [] grades){

//initialize the instance variables

this.name = name;

this.grades = grades;

}

//method to return the name of the student

public String getName(){

//return the name

return this.name;

}

//method to calculate the average of the grades

public double getAverage(){

double [] grades = this.grades;

//initialize some needed variables

double sum = 0;

double average = 0;

//loop through the grades array and add each element to the sum variable

for(int i =0; i < grades.length; i++){

sum += grades[0];

}

//calculate the average

average = sum / grades.length;

//return the average grade

return average;

}

//method the calculate the letter grade from the average

public char getLetterGrade(){

//initialize some variables

double average = this.getAverage();

char letterGrade;

//check the average and determine its corresponding letter grade

if(average >= 40 && average < 45){

letterGrade = 'E';

}

else if(average >= 45 && average < 50){

letterGrade = 'D';

}

else if(average >= 50 && average < 60){

letterGrade = 'C';

}

else if(average >= 60 && average < 70){

letterGrade = 'B';

}

else if(average >= 70 && average <= 100){

letterGrade = 'A';

}

else {

letterGrade = 'F';

}

//return the letter grade

return letterGrade;

}

} //End of the Grade class

Sample Output:

Your name is John

Your average score is 23.0

Your letter grade is F

Step-by-step explanation:

The code above is written in Java and it contains comments explaining important parts of the code. It also contains a sample output got from running the program. To run this on your machine, copy the code and save in a file named GradeTest.java

User Melissa Jenner
by
6.5k points