集合练习——Map部分
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了集合练习——Map部分相关的知识,希望对你有一定的参考价值。
练习:
输入诗的名称查询出诗的内容,当输入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("不存在该诗,或者收录不完整。"); } } }
以上是关于集合练习——Map部分的主要内容,如果未能解决你的问题,请参考以下文章