練習: 輸入詩的名稱查詢出詩的內容,當輸入exit時,退出程式,“春曉”,“靜夜思”,“鵝”。 package CollectionPart; public class Poetry { private String title; private String poet; private Strin
練習:
輸入詩的名稱查詢出詩的內容,當輸入exit時,退出程式,“春曉”,“靜夜思”,“鵝”。
package CollectionPart; public class Poetry { private String title; private String poet; private String content; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPoet() { return poet; } public void setPoet(String poet) { this.poet = poet; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "Poetry [title=" + title + ", poet=" + poet + ", content=" + content + "]"; } public Poetry(String title, String poet, String content) { super(); this.title = title; this.poet = poet; this.content = content; } public Poetry() { super(); } }
package CollectionPart; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Map1 { public static void main(String[] args) { Poetry p1 = new Poetry("春曉","孟浩然","春眠不覺曉,處處聞啼鳥。夜來風雨聲,花落知多少。"); Poetry p2 = new Poetry("靜夜思","李白","床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。"); Poetry p3 = new Poetry("詠鵝","駱賓王","鵝鵝鵝,曲項向天歌。白毛浮綠水,紅掌撥清波。"); Map<String,Poetry> myMap = new HashMap<String,Poetry>(); myMap.put(p1.getTitle(), p1); myMap.put(p2.getTitle(), p2); myMap.put(p3.getTitle(), p3); Scanner in = new Scanner(System.in); String string=null; do{ System.out.println("請輸入要查找的詩歌的名稱:"); String name = in.nextLine(); findThePoem(myMap,name); System.out.println("是否繼續查找?"); string = in.nextLine(); }while(string.equals("是")); } private static void findThePoem(Map<String, Poetry> myMap, String name) { if(myMap.containsKey(name)){ System.out.println("詩歌內容為:"); System.out.println(myMap.get(name).getContent()); }else{ System.out.println("不存在該詩,或者收錄不完整。"); } } }