gpt4 book ai didi

java - 改变HashMap键的具体值

转载 作者:行者123 更新时间:2023-12-02 02:16:08 25 4
gpt4 key购买 nike

我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com