简体   繁体   English

我已经编写了这段代码,但它确实输出了与 sam 键值对关联的值? 请告诉我如何获得山姆的价值?

[英]I have written this code but it does output the value associated with sam key value pair? please tell me how to get the value of sam?

public static void main(String[] argh) {
  Map<String, Integer> myMap = new HashMap<String, Integer>();
  Scanner in = new Scanner(System.in);
  int n = in.nextInt();
  String name = "sam";
  int phone = 0;
  for (int i = 0; i < n; i++) {
    name = in.next();
    phone = in.nextInt();
    myMap.put(name, phone);

    while (in.hasNext()) {
      String s = in.next();
      if (myMap.containsKey(s)) {
        System.out.println(name + "=" + phone);
      } else {
        System.out.println("Not found");
      }
    }
    in.close();
  }
}

I have written this code but it does output the value associated with sam key value pair?我已经编写了这段代码,但它确实输出了与 sam 键值对关联的值?

please tell me how to get the value of sam?请告诉我如何获得山姆的价值?

Here:这里:

    if(myMap.containsKey(s)){
        System.out.println(name+"="+ phone );
    }

You're checking if the map contains the s key, and then printing whatever is in the name and phone variables.您正在检查地图是否包含s键,然后打印namephone变量中的任何内容。

Instead, actually get the phone number associated with s :相反,实际获取与s关联的电话号码:

    if(myMap.containsKey(s)){
        System.out.println(s+"="+ myMap.get(s) );
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM