我有HashMap,其中key是bird specie,value是感知数量。这是我的代码:
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。
例如: 扫描仪正在询问&#34;感知到了什么?&#34;并且输出是&#34; hawk&#34;。那么程序应该改变关键&#34; hawk(buteo jamaicensis)&#34;从0到1的值。所以目标输出现在是:
sparrow (passeridae) : 0 perception
eagle (aquila chrysaetos) : 0 perception
hawk (buteo jamaicensis) : 1 perception
答案 0 :(得分:2)
使用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);
}
答案 1 :(得分:0)
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
if (entry.getKey().equals(perception)) {
entry.setValue(entry.getValue() + 1);
}
}