Why is it giving me an error when i'm calling it from inside the 'student class?

*I have to Create a class called student

• In the student class creates 5 instance variables to store student details for example name, age, grade, average term score and has a disability or not.

• Create a method that is accessible from only inside the class that displays all of the instance variables values.

• Create a mutator method ‘set grade’ that will update the value of grade instance variable

• Create an accessor ‘get grade’ to return the value of the grade variable*

but I'm getting an error and I didn't know how to complete the code, but what I did is:

public class Student {

String name;
private int age;
private int grade;
private int average;
private String disability;

public void StuInfo(){
name = "John";
age = 15;
grade = 71;
average = 63;
disability = "No";

    
System.out.println("Name: "+name+",Age: "+age+",Grade: "+grade+",Average: "+average );
}


public static void main(String[] args){
    StuInfo();
}
}

Please help.

2 answers

  • answered 2021-01-11 05:18 Satyendra Sharma

    You are calling non static method from static method. Create object of StuInfo by -> new StuInfo();

  • answered 2021-01-11 05:38 Spyros K

    In order to successfully compile your program you need to create first a new object of the class Student or make the stunInfo() method static. Also the java convention for method names is to start with a lowercase later, so StunInfo should better be named 'stunInfo'. A name like 'printStudentInfo()' can be considere, which would be even more readable and better shows what the method does. These notes can get your example working but it is not a complete solution to the homework posted. You need perhaps to change the access modifier of the stunInfo() method to be only accessible from within the class etc.

    public class Student {
    
    String name;
    private int age;
    private int grade;
    private int average;
    private String disability;
    
    public void Student(){
      name = "John";
      age = 15;
      grade = 71;
      average = 63;
      disability = "No";
    } // end constructor
    
    public void stunInfo(){
        System.out.println("Name: "+name+",Age: "+age+",Grade: "+grade+",Average: "+average );
    } //end stunInfo
    
    
    public static void main(String[] args){
        //Create a new student
        Student student=new Student();
        //Invoke stunInfo method
        student.stunInfo();
    } //end main
    
    } //end class