问题出在方法上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次而不是一次?
呼如林
相关分类