import java.io.*;<br />import java.util.*;</p><p>public class Test6_Map {<br />public static void main(String[] args) {<br />MyMapStu mms = new MyMapStu(new File("exp.txt"));<br />System.out.println("請輸入要尋找內容的學號!");<br />Scanner sc = new Scanner(System.in);<br />long sno = sc.nextLong();<br />Student stu2 = new Student(sno, " ");<br />if(mms.containsKey(stu2)) {<br />System.out.println("The name is "+mms.get(stu2.getNo()));</p><p>} else {<br />System.out.println("No such person!");<br />}<br />}<br />}</p><p>class Student { //簡單定義學生類<br />private Long sno;<br />private String sname;</p><p> public Student() {<br /> }<br /> public Student(Long sno, String sname) {<br /> this.sno = sno;<br /> this.sname = sname;<br /> }</p><p> public Long getNo() {<br /> return sno;<br /> }<br /> public String getName() {<br /> return sname;<br /> }</p><p>}</p><p>class MyMapStu { //定義此類主要是為了與檔案串連,從中把資料讀到map中。<br />Map<Long, String> map;</p><p>public MyMapStu(File stuInfo) {<br />if(!stuInfo.exists()) {<br />try {<br />stuInfo.createNewFile();<br />System.out.println("請建一個擁有30名學生學生資訊表!");<br />BufferedWriter fos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(stuInfo)));<br />byte[] bytes = new byte[40];<br />for(int i=0; i<30; i++) {<br />BufferedReader br = new BufferedReader(new InputStreamReader(System.in));<br />String str = new String();<br />str = br.readLine();<br />fos.write(str, 0, str.length());<br />fos.newLine();<br />}<br />fos.close();<br /> } catch(IOException e) {<br /> e.printStackTrace();<br /> }<br />}</p><p>try {<br />map = new HashMap<Long, String>();<br />BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream(stuInfo)));<br />String stmp;<br />while((stmp = fis.readLine())!=null) {<br />System.out.println(stmp);<br />String[] sArray = stmp.split(" ");<br /> Student stu = new Student(Long.parseLong(sArray[0]), sArray[1]);<br /> map.put(stu.getNo(), stu.getName());<br />}<br />fis.close();<br />System.out.println(map);<br />} catch(IOException e) {<br />e.printStackTrace();<br />}<br />}</p><p>public boolean containsKey(Student stu) {<br />if(map.containsKey(stu.getNo())) {<br />return true;<br />} else {<br />return false;<br />}<br />}</p><p>public String get(Long sno) {<br />if(map.containsKey(sno)) {<br />return map.get(sno);<br />} else {<br />return null;<br />}<br />} </p><p>}