|--需求說明ide
如題spa
|--實現思路code
一、使用map.containsKey()判斷輸入的姓名在不在map裏面,若是在就打印對象
二、遍歷全班姓名和成績,須要建立Map.entry,而後在map.entry裏面遍歷blog
|--代碼內容get
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1 public class Students { 2 public static void main(String[] args) { 3 //建立一個HashMap對象 4 HashMap<String, Integer> students = new HashMap<>(); 5 //向這個HashMap裏面添加元素 6 students.put("張三", 85); 7 students.put("李四", 59); 8 students.put("王五", 61); 9 10 //提取單個學生成績 11 System.out.println("請輸入學生姓名:"); 12 Scanner scanner = new Scanner(System.in); 13 String key = scanner.next(); 14 //判斷用戶輸入的人名是否被包含在map裏面,若是在,就打印出來,若是不在就告知不在 15 if (students.containsKey(key)) { 16 System.out.println("張三的成績是:" + students.get(key)); 17 } else { 18 System.out.println("這個班上沒有這我的"); 19 } 20 21 22 System.out.println("--------我是分隔符-------"); 23 //用key的集合遍歷該Map--加強for 24 Set set = students.entrySet(); 25 for (Object o : set) { 26 Map.Entry me = (Map.Entry) o; 27 String key1 = (String) me.getKey(); 28 int value = (int) me.getValue(); 29 System.out.println(key1+"的成績是:"+value); 30 } 31 } 32 }
|--運行結果class