Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

java - 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

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.

question from:https://stackoverflow.com/questions/65661632/why-is-it-giving-me-an-error-when-im-calling-it-from-inside-the-student-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 considered, which would be even more readable and better shows what the method does.(Improves readability) 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...