我有 HashMap,其中键是鸟类种类,值是感知数量。这是我的代码:
public class Program {
public static void main(String[] args) {
HashMap<String, Integer> species = new HashMap<>();
Scanner reader = new Scanner(System.in);
species.put("hawk (buteo jamaicensis)", 0);
species.put("eagle (aquila chrysaetos)", 0);
species.put("sparrow (passeridae)", 0);
System.out.println("Add perception");
System.out.println("What was perceived?"); //output should be "hawk"/"eagle"/"sparrow"
String perception = reader.nextLine();
// Change here the value of hashmap key.
ArrayList<String> list = new ArrayList<>();
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
System.out.println((entry.getKey()+" : "+entry.getValue()+" perception"));
}
}
我的目标是当扫描仪询问感知到的内容时,将键值从 0 更改为 1。
例如: 扫描仪询问“感知到了什么?”输出是“hawk”。然后程序应该将键“hawk (buteo jamaicensis)”值从 0 更改为 1。因此目标输出现在是:
sparrow (passeridae) : 0 perception
eagle (aquila chrysaetos) : 0 perception
hawk (buteo jamaicensis) : 1 perception
最佳答案
使用String.indexOf
检查输入字符串是否是该键的子字符串,如果是,则设置新值:
// Change here the value of hashmap key.
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
if (entry.getKey().indexOf(perception) >= 0) {
entry.setValue(entry.getValue() + 1);
}
关于java - 改变HashMap键的具体值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49275295/