首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更改HashMap密钥的特定值

更改HashMap密钥的特定值
EN

Stack Overflow用户
提问于 2018-03-14 18:28:51
回答 2查看 52关注 0票数 0

我有HashMap,其中key是鸟类种类,value是感知的数量。下面是我的代码:

代码语言:javascript
复制
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"));
    }



}

我的目标是在scanner询问感知到的内容时,将键值从0更改为1。

例如: Scanner询问“感知到了什么?”输出结果是"hawk“。然后,程序应该将键"hawk (buteo jamaicensis)“的值从0更改为1。因此,现在的目标输出应该是:

代码语言:javascript
复制
sparrow (passeridae) : 0 perception
eagle (aquila chrysaetos) : 0 perception
hawk (buteo jamaicensis) : 1 perception
EN

回答 2

Stack Overflow用户

发布于 2018-03-14 18:38:36

如果输入字符串是密钥的子串,则使用String.indexOf检查,如果是,则设置新值:

代码语言:javascript
复制
// 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);
}
票数 2
EN

Stack Overflow用户

发布于 2018-03-14 18:39:15

代码语言:javascript
复制
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
 if (entry.getKey().equals(perception)) {
 entry.setValue(entry.getValue() + 1);
 }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49275295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档