小编典典

在HashMap中搜索给定键的值

java

您如何在中搜索密钥HashMap?在此程序中,当用户输入密钥时,代码应安排在哈希图中搜索相应的值,然后进行打印。

请告诉我为什么它不起作用。

import java.util.HashMap;

import java.util.; import java.lang.;

public class Hashmapdemo  
{
    public static void main(String args[]) 
    { 
        String value; 
        HashMap hashMap = new HashMap(); 
        hashMap.put( new Integer(1),"January" ); 
        hashMap.put( new Integer(2) ,"February" ); 
        hashMap.put( new Integer(3) ,"March" ); 
        hashMap.put( new Integer(4) ,"April" ); 
        hashMap.put( new Integer(5) ,"May" ); 
        hashMap.put( new Integer(6) ,"June" ); 
        hashMap.put( new Integer(7) ,"July" );  
        hashMap.put( new Integer(8),"August" );  
        hashMap.put( new Integer(9) ,"September");  
        hashMap.put( new Integer(10),"October" );  
        hashMap.put( new Integer(11),"November" );  
        hashMap.put( new Integer(12),"December" );

        Scanner scan = new Scanner(System.in);  
        System.out.println("Enter an integer :");  
        int x = scan.nextInt();  
        value = hashMap.get("x");  
        System.out.println("Value is:" + value);  
    } 
}

阅读 259

收藏
2020-12-03

共1个答案

小编典典

只需致电get

HashMap<String, String> map = new HashMap<String, String>();
map.put("x", "y");

String value = map.get("x"); // value = "y"
2020-12-03