public class Test6_Map {
public static void main(String[] args) {
MyMapStu mms = new MyMapStu(new File("exp.txt"));
System.out.println("请输入要查找内容的学号!");
Scanner sc = new Scanner(System.in);
long sno = sc.nextLong();
Student stu2 = new Student(sno, " ");
if(mms.containsKey(stu2)) {
System.out.println("The name is "+mms.get(stu2.getNo()));
} else {
System.out.println("No such person!");
}
}
}
class Student { //简单定义学生类
private Long sno;
private String sname;
public Student() {
}
public Student(Long sno, String sname) {
this.sno = sno;
this.sname = sname;
}
public Long getNo() {
return sno;
}
public String getName() {
return sname;
}
}
class MyMapStu { //定义此类主要是为了与文件连接,从中把数据读到map中。
Map<Long, 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();
fos.write(str, 0, str.length());
fos.newLine();
}
fos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
try {
map = new HashMap<Long, String>();
BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream(stuInfo)));
String stmp;
while((stmp = fis.readLine())!=null) {
System.out.println(stmp);
String[] sArray = stmp.split(" ");
Student stu = new Student(Long.parseLong(sArray[0]), sArray[1]);
map.put(stu.getNo(), stu.getName());
}
fis.close();
System.out.println(map);
} catch(IOException e) {
e.printStackTrace();
}
}
public boolean containsKey(Student stu) {
if(map.containsKey(stu.getNo())) {
return true;
} else {
return false;
}
}
public String get(Long sno) {
if(map.containsKey(sno)) {
return map.get(sno);
} else {
return null;
}
}
}