把文件中的学生信息输出到控制台上

it2022-05-05  147

package student;

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner;

public class astudent { String name; String age; String id; String address;

public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public astudent() { super(); // TODO Auto-generated constructor stub } public astudent(String name, String age, String id, String address) { super(); this.name = name; this.age = age; this.id = id; this.address = address; } public static void addastudent(ArrayList<astudent> array){ Scanner scanner=new Scanner(System.in); System.out.println("请输入学生的学号"); String id=scanner.nextLine(); boolean flag=false; for(int i=0;i<array.size();i++){ astudent k=array.get(i); if(k.getId().equals(id)) flag=true; } if(flag) System.out.println("该系统已有该学生。"); else{ System.out.println("请输入学生的姓名"); String name=scanner.nextLine(); System.out.println("请输入学生的年龄"); String age=scanner.nextLine(); System.out.println("请输入学生的地址"); String address=scanner.nextLine(); astudent s=new astudent(); s.setId(id); s.setName(name); s.setAge(age); s.setAddress(address); array.add(s); } } public static void main(String[] args) throws IOException { ArrayList<astudent> array=new ArrayList<astudent>(); String newfile="kkk.txt"; System.out.println("请输入你要加入的学生个数"); Scanner scanner=new Scanner(System.in); String s=new String(); int k=scanner.nextInt(); for(int i=0;i<k;i++) addastudent(array); BufferedWriter bw=new BufferedWriter(new FileWriter(newfile)); BufferedReader br=new BufferedReader(new FileReader(newfile)); for(int i=0;i<array.size();i++){ astudent chs=array.get(i); StringBuilder ch=new StringBuilder(); ch.append(chs.getId()).append(",").append(chs.getName()).append(",").append(chs.getAge()).append(",").append(chs.getAddress()).append(","); bw.write(ch.toString()); bw.newLine(); bw.flush(); } bw.close(); ArrayList<astudent> array1=new ArrayList<astudent>(); while((s=br.readLine())!=null){ String[] s1=s.split(","); astudent b=new astudent(); b.setId(s1[0]); b.setName(s1[1]); b.setAge(s1[2]); b.setAddress(s1[3]); array1.add(b); System.out.println("\n"); } br.close(); for(int i=0;i<array1.size();i++){ astudent b=array1.get(i); System.out.println(b.getId()+"\t"+b.getName()+"\t"+b.getAge()+"\t"+b.getAddress()); } }

}


最新回复(0)