用java定义员工类Teacher类,包括成员变量name,sno,education,构造方法Teacher(String name,String sno,String education),并为三个成员变量设置对应的三对get、set方法,重写toString方法用于获取教师信息;2、让用户在控制台输入教师的数量,比方说输入5,则需要输入个教师的姓名、工号、学历,并构造对应的教师对象,把教师对象存入HashMap集合中,并同时存入一个文件中,教师信息录入完毕后,从文件中读出所有的教师信息,控制台信息打印如下图所示:教师信息保存在文件中的信息如下图所示:上述完成满分80分!实现方式二:实现具有如下功能界面的功能1、定义员工类Teacher类,包括成员变量name,sno,education,构造方法Teacher(String name,String sno,String education),并为三个成员变量设置对应的三对get、set方法,重写toString方法用于获取教师信息;
时间: 2024-02-17 18:02:47 浏览: 89
好的,我会为您解答这个问题。
首先,我们需要定义一个Teacher类,包括三个成员变量name、sno、education和对应的get、set方法以及一个构造方法。
```
public class Teacher {
private String name;
private String sno;
private String education;
public Teacher(String name, String sno, String education) {
this.name = name;
this.sno = sno;
this.education = education;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
@Override
public String toString() {
return "Name: " + name + ", Sno: " + sno + ", Education: " + education;
}
}
```
接下来,我们需要让用户在控制台输入教师的数量,并根据数量创建对应的教师对象,并将教师对象存入HashMap集合中,并同时存入一个文件中。最后从文件中读出所有的教师信息,并将信息打印在控制台上。
```
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Map<String, Teacher> teachers = new HashMap<>();
Scanner scanner = new Scanner(System.in);
System.out.print("请输入教师的数量:");
int count = scanner.nextInt();
scanner.nextLine();
for (int i = 1; i <= count; i++) {
System.out.println("请输入第" + i + "个教师的信息:");
System.out.print("姓名:");
String name = scanner.nextLine();
System.out.print("工号:");
String sno = scanner.nextLine();
System.out.print("学历:");
String education = scanner.nextLine();
Teacher teacher = new Teacher(name, sno, education);
teachers.put(sno, teacher);
// 将教师信息写入文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter("teachers.txt", true))) {
writer.write(name + "," + sno + "," + education + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
// 从文件中读取教师信息
try (BufferedReader reader = new BufferedReader(new FileReader("teachers.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
String name = parts[0];
String sno = parts[1];
String education = parts[2];
Teacher teacher = new Teacher(name, sno, education);
teachers.put(sno, teacher);
}
} catch (Exception e) {
e.printStackTrace();
}
// 打印教师信息
for (Teacher teacher : teachers.values()) {
System.out.println(teacher);
}
}
}
```
上述代码中,我们使用了Scanner类来读取用户输入的信息,并使用HashMap集合来存储教师对象。同时,我们使用了BufferedReader和BufferedWriter类来读取和写入文件。
最后,我们将读取到的教师信息打印在控制台上,具体格式和要求见题目描述。
希望我的回答能够帮助您解决问题。
阅读全文