我是初学者,最近 3 天开始学习 Java 编程语言。在这里,有 3 个实例变量,最后我得到了学生记录的详细信息,除了学生的年龄。我得到'0'我在这里犯了什么错误?我很抱歉这个愚蠢的问题。
public class Student{ // created class
String studentName; // DataMember or Instance variable
int age;
int rollNo;
// creating insertRecord method
void insertRecord(int age,String name,int rollno){
age=age;
studentName=name;
rollNo=rollno;
}
void displayRecord(){
System.out.println(age+""+studentName+""+rollNo);
}
public static void main(String[] args){ // main method
Student s1=new Student(); // creating object
Student s2=new Student(); // creating object
s1.insertRecord(23,"Maida",101);
s2.insertRecord(24,"Wheet",102);
s1.displayRecord();
s2.displayRecord();
}
}
输出是,
0Maida101
0Wheet102
正确代码:
public class Student{ // created class
int age;
String studentName; // DataMember or Instance variable
int rollNo;
public Student(int age,String name,int rollno){ // creating constructor
this.age=age;
this.studentName=name;
this.rollNo=rollno;
}
public String toString(){
System.out.println(age+""+studentName+""+rollNo);
return studentName;
}
public static void main(String[] args){ // main method
Student s1=new Student(23,"Maida",101); // creating object
Student s2=new Student(24,"Wheet",102); // creating object
s1.toString();
s2.toString();
}
}
Output is,
23Maida101
24Wheet102