Post

Created by @nathanedwards
 at November 1st 2023, 5:21:23 pm.

Question:

A math class is implementing a student database using a Student class in Java. The Student class has the following instance variables:

  • String name: the name of the student
  • int grade: the grade level of the student (between 1 and 12)
  • double mathAverage: the average grade the student achieved in math class

The Student class also has the following methods:

  • public Student(String name, int grade): a constructor that initializes the name and grade instance variables
  • public void setMathAverage(double average): a method that sets the mathAverage instance variable to the given average
  • public String getName(): a method that returns the name of the student
  • public int getGrade(): a method that returns the grade of the student
  • public double getMathAverage(): a method that returns the math average of the student

Your task is to implement the setMathAverage method in the Student class. The method should perform input validation to ensure that the provided average is in the range of 0 to 100 (inclusive). If the average is valid, it should be stored in the mathAverage instance variable; otherwise, the variable should be set to 0.

Write the code for the setMathAverage method in the Student class.

public class Student {
    private String name;
    private int grade;
    private double mathAverage;
    
    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }
    
    // Write the setMathAverage method here
    
    public String getName() {
        return name;
    }
    
    public int getGrade() {
        return grade;
    }
    
    public double getMathAverage() {
        return mathAverage;
    }
}

Provide your solution below:

Solution:

public void setMathAverage(double average) {
    if (average >= 0 && average <= 100) {
        mathAverage = average;
    } else {
        mathAverage = 0;
    }
}

Explanation:

The setMathAverage method takes in a double parameter called average. Inside the method, we check if average is within the valid range of 0 to 100 (inclusive) using an if statement.

If average is within the valid range, we assign the value of average to the mathAverage instance variable using the assignment operator (=).

If average is not within the valid range, we assign the value of 0 to the mathAverage instance variable using the assignment operator (=).

By using this input validation logic, we ensure that the mathAverage remains valid and consistent for each student in the database.