1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
-
- import java.util.TreeMap;
- import java.util.Set;
- import java.util.ArrayList;
- /**
- * Created by leon on 1/23/18.
- * Updated by allison on 5/30/18
- */
- public class PhoneBook {
-
- TreeMap<String, ArrayList<String>> myFriendsDigits;
-
- public PhoneBook() {
- myFriendsDigits = new TreeMap<String, ArrayList<String>>();
- }
-
- public void add(String name, String phoneNumber) {
- if (lookup(name).equals("Not Found")){
- ArrayList<String> soManyDigits = new ArrayList<String>();
- soManyDigits.add(phoneNumber);
- myFriendsDigits.put(name, soManyDigits);
- }
- else {
- ArrayList<String> soManyDigits = myFriendsDigits.get(name);
- soManyDigits.add(phoneNumber);
- }
- }
-
- public void add(String name, ArrayList<String> phoneNumbers) {
- myFriendsDigits.put(name, phoneNumbers);
- }
-
- public void remove(String name) {
- myFriendsDigits.remove(name);
- }
- public void remove(String name, int phoneNumberIndex) {
- ArrayList phoneNumbers = myFriendsDigits.get(name);
- phoneNumbers.remove(phoneNumberIndex);
- }
- public String lookup(String name) {
- ArrayList<String> phoneNumbers = myFriendsDigits.get(name);
- if (phoneNumbers != null) {
- return getPhoneNumberString(phoneNumbers);
- }
- else {
- return "Not Found";
- }
- }
-
- public String reverseLookup(String phoneNumber) {
- Set<String> names = myFriendsDigits.keySet();
- for (String name : names) {
- if (searchPhoneNumberList(myFriendsDigits.get(name), phoneNumber)){
- return name;
- }
- }
- return "Not Found";
- }
-
- public void display() {
- Set<String> names = myFriendsDigits.keySet();
- for (String name : names){
- System.out.println("Name: " + name + ": " + myFriendsDigits.get(name));
- }
- }
- private boolean searchPhoneNumberList(ArrayList<String> phoneNumbers, String theMagicNumber) {
- boolean found = false;
- for (int i = 0; i < phoneNumbers.size(); i++) {
- if (phoneNumbers.get(i).equals(theMagicNumber)) {
- found = true;
- break;
- }
- }
- return found;
- }
- private String getPhoneNumberString(ArrayList<String> phoneNumbers) {
- StringBuilder formattedNumbers = new StringBuilder();
- for (int i = 0; i < phoneNumbers.size(); i++) {
- if (i == phoneNumbers.size() - 1) {
- formattedNumbers.append(phoneNumbers.get(i));
- }
- else {
- formattedNumbers.append(phoneNumbers.get(i) + ", ");
- }
- }
- return formattedNumbers.toString();
- }
- }
|