我有HashMap,其中key是鸟类种类,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"));
}
}我的目标是在scanner询问感知到的内容时,将键值从0更改为1。
例如: Scanner询问“感知到了什么?”输出结果是"hawk“。然后,程序应该将键"hawk (buteo jamaicensis)“的值从0更改为1。因此,现在的目标输出应该是:
sparrow (passeridae) : 0 perception
eagle (aquila chrysaetos) : 0 perception
hawk (buteo jamaicensis) : 1 perception发布于 2018-03-14 18:38:36
如果输入字符串是密钥的子串,则使用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);
}发布于 2018-03-14 18:39:15
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
if (entry.getKey().equals(perception)) {
entry.setValue(entry.getValue() + 1);
}
}https://stackoverflow.com/questions/49275295
复制相似问题