IO流结合学生管理系统的练习

添加学生类信息到文本

public static void main(String[] args) throws IOException {
	// 定义学生类
	// 创建集合对象array
	ArrayList<Student> array = new ArrayList<Student>();
	addStudent(array);
	addStudent(array);
	addStudent(array);
		// 创建输出缓冲流
		BufferedWriter bw = new BufferedWriter(new FileWriter("babba.java", true));
		// 遍历集合对象array,
		for (int a = 0; a < array.size(); a++) {
			Student s = array.get(a);
			// 创建StringBuilder对象sb,用到他的append方法
			StringBuilder sb = new StringBuilder();
			sb.append(s.getId()).append(",").append(s.getName()).append(",").append(s.getAge());
			// 把上面的转换成String
			bw.write(sb.toString());
			bw.newLine();
			bw.flush();
			System.out.println(sb.toString());
		}
		bw.close();

}

public static void addStudent(ArrayList<Student> array) {
	// 创建键盘输入
	Scanner sc = new Scanner(System.in);

	String id;
	while (true) {
		// 创建变量接收数据
		System.out.println("id:");
		id = sc.nextLine();

		int index = -1;
		for (int a = 0; a < array.size(); a++) {
			Student s = array.get(a);
			if (s.getId().equals(id)) {
				index = a;
			}

		}
		if (index == -1) {
			break;
		} else {
			System.out.println("学号有重复");
			return;
		}
	}

	System.out.println("name:");
	String name = sc.nextLine();
	System.out.println("age:");
	String age = sc.nextLine();
	// 把上面的数据添加到学生类
	Student s = new Student();
	s.setId(id);
	s.setAge(age);
	s.setName(name);
	// 添加到集合
	array.add(s);
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44063001/article/details/85246036