Skip to content
Advertisement

“grade” cannot be resolved to a variable

I have this exercise and the question is how can I solve the error “grade” cannot be resolved to a variable, without declare it in the class teacher. I suppose is the only error in my code. It is evident for me WHY then in my output only the grade variable is not assigned, but I don’t know HOW to solve it.

public class App {
    public static void main(String[] args) throws Exception {

        Student studentOne = new Student("FraPedu");
        Student studentTwo = new Student("FraIla");
        Teacher teacherOne = new Teacher();
        
        teacherOne.teacherName = "Tiziana";

        teacherOne.assignGrade(studentOne,10);
        teacherOne.assignGrade(studentTwo,10);
        studentOne.getStudentDetails();
        studentTwo.getStudentDetails();
    }
}

public class Student {

    public String name;
    public int grade;

    public Student(String studentName) {

        System.out.println("Student object has been created succesfully!");
        name = studentName;
    }

    public void getStudentDetails() {

        System.out.println("Student name and grade: " + name + " " + grade);        
    }
}

public class Teacher {

    public String teacherName;

    public Teacher() {

        System.out.println("Teacher object has been created succesfully!");
    }

    public void assignGrade(Student alum, int finalGrade) {

        grade = finalGrade; 
    }
}

Answer

You need to assign the grade to the Student object you are passing to the assignGrade method.

public class Teacher {

    public String teacherName;

    public Teacher() {

        System.out.println("Teacher object has been created succesfully!");
    }

    public void assignGrade(Student alum, int finalGrade) {

        alum.grade = finalGrade; // << this is the line I changed
    }
}
Advertisement