Java第十六天(三)
从控制台录入信息至文件实例
用户类
/**
* Student类
*/
//implements Comparable<Student>
public class Student implements Comparable<Student>{
//定义学生类成员变量
private Integer id;
private String name;
private Integer age;
/*
* 封装学生类的成员变量
*/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
//生成相应的构造器
public Student(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
//重写toString方法
@Override
public String toString() {
return "Student [学号=" + id + ", 姓名=" + name + ", 年龄=" + age + "]"+" ";
}
/**
* 重写Comparable方法
* 首先比较学号,按照学号升序进行排序
* 若学号相同,比较年龄,年龄小的在前
* 若学号、年龄都相同,比较姓名
*/
@Override
public int compareTo(Student stu) {
//先比较学号
int val = this.id - stu.id;
if(val == 0) {
//若学号相同比较年龄
val = this.age - stu.age;
if(val == 0) {
//判断两个对象的姓名是否为空
if(this.name != null && stu.name != null) {
//若学号、年龄都相同,比较姓名
val = this.name.compareTo(stu.name);
}
}
}
return val;
}
}
实现需求方法类
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeSet;
public class ScannerStu {
public static void main(String[] args) {
scannerStu();
}
public static void scannerStu() {
// 创建学生集合
TreeSet<Student> stuTreeSet = new TreeSet<Student>();
// 创建控制台输入对象
Scanner sc = new Scanner(System.in);
System.out.println("请输入需要录入学生信息的人数:");
// 定义输入学生数量目标人数
int count = sc.nextInt();
for(int i = 1;i<=count;i++) {
sc = new Scanner(System.in);
System.out.println("现在是第"+i+"位学生");
System.out.println("请输入学生id:");
// 获得学生id
Integer id = sc.nextInt();
// 此处使用nextLine目的是为了清空缓冲区
sc.nextLine();
System.out.println("请输入学生姓名:");
// 获得学生姓名
String name = sc.nextLine();
System.out.println("请输入学生年龄:");
// 获得学生年龄
Integer age = sc.nextInt();
// 创建学生对象
Student st = new Student(id, name, age);
// 将学生加入到集合中
stuTreeSet.add(st);
}
BufferedWriter bw = null;
try {
//创建高效缓冲区输出流
bw = new BufferedWriter(new FileWriter("Test.txt",true));
//将目标数据写入文件
for(Student s:stuTreeSet) {
bw.write(s.getId()+" "+s.getName()+" "+s.getAge());
bw.newLine();
}
//清空缓冲区
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bw != null) {
try {
//当关闭BufferWriter时会自动关闭FileWriter
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}