将三个代码片段整合成一个完整的程序代码?
时间: 2024-11-17 16:29:44 浏览: 6
如何使多个数据库的表格合并成一张表并显示在一个gridview中.doc
当然可以。这是一个将三个代码片段整合成一个完整Java程序的例子,包括`Person`类及其子类`Student`和`Teacher`,以及主函数`main`来接收用户输入并输出相应的信息:
```java
// 定义Person类
public class Person {
private String name;
private int age;
// 构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter and setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
// toString方法
@Override
public String toString() {
return "Name: " + name + ", Age: " + age;
}
}
// 定义Student类
public class Student extends Person {
private int electiveCourses;
public Student(String name, int age, int electiveCourses) {
super(name, age);
this.electiveCourses = electiveCourses;
}
// getter for electiveCourses
public int getElectiveCourses() { return electiveCourses; }
// setter for electiveCourses (省略,因为已经有了默认的setter)
// override toString to include elective courses
@Override
public String toString() {
return super.toString() + ", Elective Courses: " + electiveCourses;
}
}
// 定义Teacher类
public class Teacher extends Person {
private String teachingSubject;
public Teacher(String name, int age, String teachingSubject) {
super(name, age);
this.teachingSubject = teachingSubject;
}
// getter for teachingSubject
public String getTeachingSubject() { return teachingSubject; }
// setter for teachingSubject (省略,因为已经有了默认的setter)
// override toString to include teaching subject
@Override
public String toString() {
return super.toString() + ", Teaching Subject: " + teachingSubject;
}
}
// 主函数
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入人员类型(Teacher或Student):");
String userType = scanner.next();
switch (userType) {
case "Student":
System.out.println("请输入姓名 年龄 选修课程数: ");
String[] studentInfo = scanner.nextLine().split(" ");
String studentName = studentInfo[0];
int studentAge = Integer.parseInt(studentInfo[1]);
int studentCourses = Integer.parseInt(studentInfo[2]);
Student student = new Student(studentName, studentAge, studentCourses);
System.out.println(student.toString());
break;
case "Teacher":
System.out.println("请输入姓名 年龄 教授课程: ");
String[] teacherInfo = scanner.nextLine().split(" ");
String teacherName = teacherInfo[0];
int teacherAge = Integer.parseInt(teacherInfo[1]);
String teacherSubject = teacherInfo[2];
Teacher teacher = new Teacher(teacherName, teacherAge, teacherSubject);
System.out.println(teacher.toString());
break;
default:
System.out.println("无效的类型");
break;
}
scanner.close();
}
}
```
这个程序会根据用户的输入,创建对应的`Student`或`Teacher`对象,并打印出相关信息。如果输入的是其他类型,则会显示错误消息。
阅读全文