为什么年龄不在此计划中显示?

时间:2013-09-20 05:39:11

标签: java

我是初学者,从过去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

2 个答案:

答案 0 :(得分:7)

将年龄分配给实例变量

this.age=age;

否则,您只需将age参数指定给age参数即可。 这没有效果。

答案 1 :(得分: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