用java代码编写一个程序,在IDEA里面实现功能,要求设计一个学生student类,包含学号、姓名、出生日期、性别等字段 从src中的input.txt文件(内容:1001 张三 1998-01-18 男 1002 李四 1999-04-28 男 1003 王五 1998
时间: 2024-02-15 09:04:19 浏览: 74
好的,以下是Java代码实现:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student {
private String id;
private String name;
private LocalDate birthdate;
private String gender;
public Student(String id, String name, LocalDate birthdate, String gender) {
this.id = id;
this.name = name;
this.birthdate = birthdate;
this.gender = gender;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBirthdate() {
return birthdate;
}
public void setBirthdate(LocalDate birthdate) {
this.birthdate = birthdate;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", birthdate=" + birthdate +
", gender='" + gender + '\'' +
'}';
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
File inputFile = new File("src/input.txt");
try {
Scanner scanner = new Scanner(inputFile);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(" ");
String id = parts[0];
String name = parts[1];
LocalDate birthdate = LocalDate.parse(parts[2], formatter);
String gender = parts[3];
Student student = new Student(id, name, birthdate, gender);
students.add(student);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (Student student : students) {
System.out.println(student);
}
}
}
```
这个程序会从`src`目录下的`input.txt`文件中读取学生信息,创建`Student`对象,并将所有学生对象存储在一个`List`中。然后遍历这个`List`,将所有学生信息输出到控制台。
你可以在IDEA中打开这个程序,运行它,并确保`src/input.txt`文件中包含了正确的学生信息。
阅读全文