以下是一个简单的Java程序,用于输入和显示学生和教师的数据。程序中定义了一个基类Person
,以及两个派生类Student
和Teacher
。每个类都包含了输入和显示数据的方法。
importjava.util.Scanner; //基类Person class Person{ protected intno; //编号 protectedStringname; //姓名 publicPerson( intno,Stringname){ this.no=no; this.name=name;} public voidinput(){System.out.print( "请输入编号:"); this.no=Integer.parseInt(System.in.nextLine());System.out.print( "请输入姓名:"); this.name=System.in.nextLine();} public voiddisplay(){System.out.println( "编号为:"+no);System.out.println( "姓名为:"+name);}} //学生类Student class Student extends Person{ private intclassId; //班号 private doublescore; //成绩 publicStudent( intno,Stringname, intclassId, doublescore){ super(no,name); this.classId=classId; this.score=score;} public voidinputStudentData(){ super.input();System.out.print( "请输入班号:"); this.classId=Integer.parseInt(System.in.nextLine());System.out.print( "请输入成绩:"); this.score=Double.parseDouble(System.in.nextLine());} @Override public voiddisplay(){ super.display();System.out.println( "班号为:"+classId);System.out.println( "成绩为:"+score);}} //教师类Teacher class Teacher extends Person{ privateStringtitle; //职称 privateStringdepartment; //部门 publicTeacher( intno,Stringname,Stringtitle,Stringdepartment){ super(no,name); this.title=title; this.department=department;} public voidinputTeacherData(){ super.input();System.out.print( "请输入职称:"); this.title=System.in.nextLine();System.out.print( "请输入部门:"); this.department=System.in.nextLine();} @Override public voiddisplay(){ super.display();System.out.println( "职称为:"+title);System.out.println( "部门为:"+department);}} //主类 public class Main{ public static voidmain(String[]args){ Scanner scanner = new Scanner(System.in); //输入学生数据System.out.println( "请输入学生数量:"); int studentCount =scanner.nextInt();Student[]students= new Student[studentCount]; for( int i = 0;i<studentCount;i++){System.out.println( "请输入第"+(i+ 1)+ "个学生的信息:");students[i]= new Student( 0, "", 0, 0.0);students[i].inputStudentData();students[i].display();} //输入教师数据System.out.println( "请输入教师数量:"); int teacherCount =scanner.nextInt();Teacher[]teachers= new Teacher[teacherCount]; for( int i = 0;i<teacherCount;i++){System.out.println( "请输入第"+(i+ 1)+ "个教师的信息:");teachers[i]= new Teacher( 0, "", "", "");teachers[i].inputTeacherData();teachers[i].display();}scanner.close();}}
说明:
Person类:包含编号和姓名,提供输入和显示方法。
Student类:继承自Person类,包含班号和成绩,重写了输入和显示方法。
Teacher类:继承自Person类,包含职称和部门,重写了输入和显示方法。
Main类:包含主函数