-2

I need to write a code which finds a phone number from an array list when a name is given. Here is what i currently have:

public class Person {

    private String name;
    private String number;

    public Person(String name, String number) {
        this.name = name;
        this.number = number;
    }

    public String getName() {
        return this.name;
    }    

    public String getNumber() {
        return this.number;
    }


    public String toString() {
        return "" + getName()+ "  number: " + getNumber();
    }    
}

And here is the class for phone numbers list:

import java.util.ArrayList;

public class Numbers {
    private ArrayList<Person> memo;

    public Numbers() {
        this.memo = new ArrayList<>();
    }

    public void addnew(String name, String number) {
        Person newperson = new Person (name, number);
        this.memo.add(newperson);      
    }
}
nhouser9
  • 6,730
  • 3
  • 21
  • 42
osXso
  • 1
  • 1
  • 4
    You should start with a for loop. You've two classes... Where's the search code you've attempted? – OneCricketeer Jun 03 '17 at 23:18
  • 1
    Possible duplicate of [Implement binary search in objects](https://stackoverflow.com/questions/901944/implement-binary-search-in-objects) – OneCricketeer Jun 03 '17 at 23:20
  • 1
    If I gave you a piece of paper with a list of names and phone numbers, how would you find the number for a specific name? Think about the steps you need to take to solve this problem manually then describe those steps in words. – Code-Apprentice Jun 03 '17 at 23:40

1 Answers1

0

Use this method

public String FindNumber(String UserName){
   for(Person p : [ArrayList<Person>]) {
      if (UserName.equals( p.getName())){
         return p.getNumber();
      }
   }
   return "NaN";
}

this object [ArrayList<Person>] Must be the reference of your list

in your case:

you need to fix the builder

public Numbers() {
    this.memo = new ArrayList<Person>();
}

Your function will be

public String FindNumber(String UserName){
   for(Person p : this.memo ) {
      if (UserName.equals( p.getName())){
         return p.getNumber();
      }
   }
   return "NaN";
}