通过输入 HashMap 值获取 HashMap 键未按预期工作

问题出在方法上getName()


public class Phonebook implements PhonebookInterface {


    private Map<String, Set<String>> phonebook;

    private Map<String, Address> address;


    public Phonebook() {

        this.phonebook = new HashMap<String, Set<String>>();

        this.address = new HashMap<String, Address>();

    }


    @Override

    public void addNumber(String person, String number) {

        if (!this.phonebook.containsKey(person)) {

            this.phonebook.put(person, new HashSet<String>());

        }


        this.phonebook.get(person).add(number);

    }


    @Override

    public void getName(String number) {

        for (String person : this.phonebook.keySet()) {

            if (this.phonebook.get(person).contains(number)) {

                System.out.println(" " + person);

            } else {

                System.out.println("  not found");

            }

        }

    }


    @Override

    public void getNumber(String person) {

        try {

            for (String n : this.phonebook.get(person)) {

                if (this.phonebook.get(person).size() > 1) {

                    System.out.println(" " + n);

                } else {

                    System.out.println("number: " + n);

                }

            }

        } catch (Exception e) {

            System.out.println("  not found");

        }

    }


    public void addAddress(String person, String street, String city) {

        this.address.put(person, new Address(street, city));

    }


预期的输出是:

搜索号码:

Pekka:

014-1234

015-5344

Matti:

号码:013-4321


通过电话号码搜索人:

Matti

not found


但输出是:

搜索号码:

Pekka:

014-1234

015-5344

Matti:

号码:013-4321


通过电话号码搜索人:

未找到

Matti

not found

未找到


为什么输出打印“找不到”3次而不是一次?


Helenr
浏览 61回答 1
1回答

呼如林

您遍历 的所有键Map并将相应的值与您要查找的值进行比较。如果没有匹配,则打印“未找到”。您Map有两个键,因此如果您正在搜索 中存在的值Map,您将打印匹配的键,但您还将为另一个键打印“未找到”。如果您正在搜索 中不存在的值Map,您将打印两次“未找到”(每个键一次)。您应该只在遍历所有键后打印“未找到”:public void getName(String number) {&nbsp; &nbsp;&nbsp; &nbsp; for (String person : this.phonebook.keySet()) {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (this.phonebook.get(person).contains(number)) {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(" " + person);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("&nbsp; not found");&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java