如何向hashmap添加元素?

时间:2016-11-29 03:41:41

标签: java hashmap key key-value

我是HashMaps的新手。我想知道我是否可以添加询问用户他或她想要的密钥以及他们想要的价值。到目前为止,我正在打印出HashMap,但出于某种原因,当我要求视图返回null的值时,当我尝试删除键时,它也不会删除它。

import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {
  public static void main (String [] args){
    //declaring a hashmap   
    HashMap<Integer, String> hm = new HashMap<Integer, String>();

    //adding elements to the hashmap
    hm.put(1, "Josh");
    hm.put(2, "Max");
    hm.put(3, "Karan");

    //declaring the Scanner
    Scanner sc = new Scanner(System.in);
    System.out.println("Would you like to add Elements to the hashmap?");
    String scYN = sc.nextLine();
    scYN = scYN.toLowerCase();
    if(scYN.equals("yes")) {
        System.out.println("What would the key to be?");
        int key = sc.nextInt();
        sc.nextLine();
        System.out.println("What would the value to be?");
        String val = sc.nextLine();
        hm.put(key, val);           
    }else if (scYN.equals("no")) {
        System.out.println("False");
    }else{
        System.out.println("False");
    }

    //displaying content 
    Set set = hm.entrySet();
    Iterator iterator = set.iterator();
    while(iterator.hasNext()){
        Map.Entry mentry = (Map.Entry)iterator.next();
        System.out.print("Key is: "+ mentry.getKey() + " & Value is: ");
        System.out.println(mentry.getValue());
    }

    /* Get values based on key*/

    System.out.println("What value would you like to find?");
    String fVal = sc.nextLine();        
    String var= hm.get(fVal);
    System.out.println("Value at index " + fVal + " is: "+ var);

    /* Remove values based on key*/

    System.out.println("Would you like to remove a key?");
    String remKey = sc.nextLine();
    hm.remove(remKey);
    System.out.println("Map key and values after removal:");
    Set set2 = hm.entrySet();
    Iterator iterator2 = set2.iterator();
    while(iterator2.hasNext()) {
        Map.Entry mentry2 = (Map.Entry)iterator2.next();
        System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
        System.out.println(mentry2.getValue());
    }

}

}

感谢您的时间

1 个答案:

答案 0 :(得分:2)

它为您提供空值,因为当您使用 get()时,作为参数传递的键( fVal )是字符串,而在Hashmap中,其键被定义为整数

要解决此问题,请将fVal变量设为整数,以获取 nextInt()

>>> [ n*2 for n in randomList if n % 2]
[6, 10, 14, 22]

你在征求数据录入时这样做了,“关键是什么?”。在提示搜索条件时,请执行相同的操作,“您希望找到什么值?”,并在提示删除时,“是否要删除密钥?”。