在HashMap中搜索给定键的值 [英] Search a value for a given key in a HashMap

查看:90
本文介绍了在HashMap中搜索给定键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 HashMap 中搜索密钥?在这个程序中,当用户输入一个键时,代码应该安排在hashmap中搜索相应的值,然后打印出来。

How do you search for a key in a HashMap? In this program, when the user enters a key the code should arrange to search the hashmap for the corresponding value and then print it.

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

Please tell me why it's not working.

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);  
    } 
} 


推荐答案

致电 get

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

String value = map.get("x"); // value = "y"

这篇关于在HashMap中搜索给定键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆