java从控制台输入Student类的信息,包括学号、姓名、年龄,如输入错误,提示用户重新输入;实现保存对象到文件和从文件读出对象并显示。
时间: 2024-10-29 19:16:19 浏览: 23
Java实验五输入输出流
在Java中,你可以通过Scanner类从控制台获取用户的输入,并创建Student对象实例。首先,你需要定义一个Student类,包含学号、姓名和年龄属性,以及相应的构造函数。然后,你可以编写一个主程序来处理用户的输入和文件操作。
以下是简单的步骤:
1. **定义Student类**:
```java
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// getters and setters for id, name, and age
}
```
2. **获取用户输入并验证**:
```java
import java.util.Scanner;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请输入学生信息(学号 id, 姓名 name, 年龄 age),格式:id name age");
if (scanner.hasNextInt() && scanner.hasNextString() && scanner.hasNextInt()) {
int id = scanner.nextInt();
String name = scanner.next();
int age = scanner.nextInt();
// 创建并检查输入是否合法
try {
Student student = new Student(id, name, age);
break; // 输入正确,跳出循环
} catch (Exception e) {
System.out.println("输入有误,请重新输入!");
scanner.nextLine(); // 清除上一行输入
}
} else {
System.out.println("输入格式错误,请重新输入!");
}
}
// 存储到文件
saveToFile(student, "students.txt");
}
private static void saveToFile(Student student, String fileName) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
oos.writeObject(student);
System.out.println("学生信息已保存到文件.");
} catch (IOException e) {
System.out.println("保存失败:" + e.getMessage());
}
}
```
3. **从文件读取对象**:
```java
public static Student readFromFile(String fileName) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
return (Student) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("加载失败:" + e.getMessage());
return null;
}
}
// 显示读取的学生信息
public static void displayStudent(Student student) {
System.out.printf("学号:%d, 姓名:%s, 年龄:%d\n", student.getId(), student.getName(), student.getAge());
}
public static void main(String[] args) {
Student loadedStudent = readFromFile("students.txt");
if (loadedStudent != null) {
displayStudent(loadedStudent);
} else {
System.out.println("未找到文件或文件内容无效");
}
}
```
阅读全文