java - 在 HashMap 中搜索给定键的值

标签 java

如何在 HashMap 中搜索键?在这个程序中,当用户输入一个键时,代码应该安排在 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);  
    } 
} 

最佳答案

只需调用 get :

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

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

关于java - 在 HashMap 中搜索给定键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051486/

相关文章:

java - Corba 非阻塞球体

java - Sparql 与 Java Jena

java - 如何实现阻塞线程池执行器?

java - 检测用户输入的单词是否与Java中数组列表中的字符串匹配

java - nutch 爬虫正在爬行“as”

java - 如何从json文件中只获取部分属性?

java - JDBC-ORA-01861 : literal does not match format string 01861

java - 使用Java从二进制文件中读取整数值

java - 在没有所有繁忙工作的情况下模拟 Java 中的拼写错误

java - Rabin-Karp 不适用于大素数(给出错误的输出)