-1

我是初学者,最近 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
4

2 回答 2

7

将年龄分配给实例变量

this.age=age;

否则,您只需将年龄参数分配给年龄参数。那没有效果。

于 2013-09-20T05:39:50.307 回答
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){ 
this.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,"Meena",101);
s2.insertRecord(24,"Nisha",102);
s1.displayRecord();
s2.displayRecord();

}
}

输出

23Meena101
24Nisha102
于 2013-09-20T05:43:47.293 回答