您好,我创建了一个层次结构,其中我有一个名为person的超类和两个子类即学生和老师现在我想以5个学生为对象,并获取所有信息并制作一个方法来打印一些细节比如名字现在我写了一些代码,但问题是所有对象都显示相同的信息..请帮助我,并给我详细说明我做错了...提前谢谢 我的代码如下:
public class L9t2 {
public static void main(String[] args){
putdetails d=new putdetails();
d.pdetails();
d.printdetail();
}
}
class putdetails{
Student[] st=new Student[3];
void pdetails(){
String n,ln,a,r,d,pno,t,ci;
double gpa;
Scanner input=new Scanner(System.in);
int i;
Student tst=new Student();
// Student[] st=new Student[5];
// for( i=0;i<5;i++){
// st[i]=new Student();
// Student ch;
for(i=0;i<3;i++ ){
System.out.println("Put the Information of Student "+(i+1)+": ");
System.out.print("Enter name: ");
tst.setname(n=input.next());
System.out.print("Enter last name: ");
tst.setlname(ln=input.next());
System.out.print("Enter address: ");
tst.setaddress(a=input.nextLine());
System.out.print("Enter roll no: ");
tst.setrollno(r=input.nextLine());
System.out.print("Enter GPA: ");
tst.setgpa(gpa=input.nextDouble());
st[i]=tst;
/* System.out.println(ch.getname());
System.out.println(tst.getname());*/
}
}
void printdetail(){
for(int i=0;i<2;i++){
System.out.println("Name of "+(1)+"Student: "+st[i].getname());
}
}
}
class person{
private String name,address,l_name;
void setname(String name){
this.name=name;
}
void setaddress(String address){
this.address=address;
}
void setlname(String l_name){
this.l_name=l_name;
}
String getname(){
return name;
}
String getlname(){
return l_name;
}
}
class Student extends person{
private String rollno;
private double gpa;
void setrollno(String rollno){
this.rollno=rollno;
}
void setgpa(double gpa){
this.gpa=gpa;
}
String getrollno(){
return rollno;
}
}
class Teacher extends person{
private String degree,pno;
void getdegree(String degree){
this.degree=degree;
}
void getpno(String pno){
this.pno=pno;
}
}
class Course{
private String title,CourseID;
void settitle(String title){
this.title=title;
}
void setcourseid(String CourseID){
this.CourseID=CourseID;
}
String gettitle(){
return title;
}
}