案例要求:
①从控制台接收3名学员的信息,每条信息存储到一个Student对象中,
②将多个Student对象存储到一个集合中
③将集合中学员信息存储到文件Student.txt中。
每名学员信息存储一行,多个属性值中间用空格隔开
public class T3 {
public static void main(String[] args) throws Exception {
recive();
}
//接受学生信息并存储
public static void recive() throws Exception {
ArrayList<Student> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("请输入第"+(i+1)+"学生的姓名");
String name = sc.next();
System.out.println("请输入第"+(i+1)+"学生的年龄");
int age = sc.nextInt();
list.add(new Student(name,age));
}
FileWriter fw = new FileWriter("Student.txt");
BufferedWriter bw = new BufferedWriter(fw) ;
for (Student student : list) {
String name = student.name;
int age = student.age;
bw.write(name+" "+age);
bw.newLine();
bw.flush();
}
bw.close();
}
}
//学生类
class Student{
String name;
int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}