[英]How do you add elements to a hashmap?
我是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());
}
}
}
感谢您的时间
它给你一个空值,因为当你使用get()时 ,作为paramanter( fVal )传递的键是一个String ,而在Hashmap中它的键被定义为一个Integer 。
要解决此问题,请将fVal变量设置为获取nextInt()的Integer
int fVal = sc.nextInt();
你在征求数据录入时这样做了,“关键是什么?”。 在提示搜索条件时,“您想要找到什么值?”,并在提示删除时,“是否要删除密钥?”时执行相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.