13.2 完成一个学生管理程序,使用学号作为键添加5个学生对象,并可以将全部信息保存在文件中,可以实现对学生信息的学号查找、输出全部学生信息的功能。
package book;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import java.util.Iterator;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
class Student {
private int number;
private String name;
private float score;
public Student(int number, String name, float score) {
this.setNumber(number);
this.setName(name);
this.setScore(score);
}
public void setNumber(int number) {
this.number = number;
}
public void setName(String name) {
this.name = name;
}
public void setScore(float score) {
this.score = score;
}
public int getNumber() {
return this.number;
}
public String getName() {
return this.name;
}
public float getScore() {
return this.score;
}
public String toString() {
return "学号:" + this.number + " 姓名:" + this.name + " 成绩:" + this.score;
}
}
public class JiOu {
public static void main(String[] args) throws Exception {
File f = new File("D:" + File.separator + "student.txt");
OutputStream out = new FileOutputStream(f);
Student stu1 = new Student(20180803, "张三", 93);
Student stu2 = new Student(20180804, "李四", 94);
Student stu3 = new Student(20180805, "王五", 95);
Student stu4 = new Student(20180806, "赵六", 96);
Student stu5 = new Student(20180807, "钱七", 97);
Map<String, Student> map = new HashMap<String, Student>();
map.put("1", stu1);
map.put("2", stu2);
map.put("3", stu3);
map.put("4", stu4);
map.put("5", stu5);
String str = map.toString();
byte b[] = str.getBytes();
out.write(b);
out.close();
Student val = map.get("1");
System.out.println("1号学生的信息是 " + val);
System.out.println("全部的学生信息为:");
Collection<Student> values = map.values();
Iterator<Student> iter = values.iterator();
while (iter.hasNext()) {
Student str1 = iter.next();
System.out.println(str1);
}
}
}
运行结果:
1号学生的信息是 学号:20180803 姓名:张三 成绩:93.0
全部的学生信息为:
学号:20180803 姓名:张三 成绩:93.0
学号:20180804 姓名:李四 成绩:94.0
学号:20180805 姓名:王五 成绩:95.0
学号:20180806 姓名:赵六 成绩:96.0
学号:20180807 姓名:钱七 成绩:97.0
原文地址:https://blog.csdn.net/Lakers1989/article/details/78239081