如题,这是个让我写了近5个小时的程序,学习 I/O 和 collection。
记下这个程序,来记住现在的我,希望不久再看这个程序时,发现自己的水平有所提高。
程序中还有问题待解决。
- import java.io.*;
- import java.util.*;
- public class Test6_Map {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- MyMapStu mms = new MyMapStu(new File("C://Users//taotao//Desktop//exp.txt"));
- Student sno = new Student("91328088", "taotao");
- //sno = sc.next();
- if(mms.containsKey(sno)) {
- System.out.println("found");
- } else {
- System.out.println("not found");
- }
- }
- }
- class Student { //简单定义学生类
- private String sno;
- private String sname;
- public Student() {
- }
- public Student(String sno, String sname) {
- this.sno = sno;
- this.sname = sname;
- }
- public String getNo() {
- return sno;
- }
- public String getName() {
- return sname;
- }
- }
- class MyMapStu extends Student { //定义此类主要是为了与文件连接,从中把数据读到map中。
- Map<String, String> map;
- public MyMapStu(File stuInfo) {
- if(!stuInfo.exists()) {
- try {
- stuInfo.createNewFile();
- System.out.println("请建一个拥有30名学生学生信息表!");
- BufferedWriter fos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(stuInfo)));
- byte[] bytes = new byte[40];
- for(int i=0; i<30; i++) {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String str = new String();
- str = br.readLine();
- str += "/n";
- //bytes = str.getBytes(str);
- fos.write(str, 0, str.length());
- fos.write('/n');
- }
- fos.close();
- } catch(IOException e) {
- e.printStackTrace();
- }
- }
- try {
- map = new HashMap<String, String>();
- BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream(stuInfo)));
- String stmp = fis.readLine();
- String[] sArray = stmp.split(" ");
- Student stu = new Student(sArray[0], sArray[1]);
- map.put(stu.getNo(), stu.getName());
- } catch(IOException e) {
- e.printStackTrace();
- }
- }
- public boolean containsKey(Student sno) {
- if(this.map.containsKey(sno)) {
- return true;
- } else {
- return false;
- }
- }
- }
containsKey()方法还是有问题,无论怎样都不会找到表中有的数据