使用ArrayList的Java PhoneBook

时间:2015-03-16 19:07:32

标签: java arraylist

我试图使用数组列表制作电话簿,但我没有得到正确的输出,这是我的代码,谢谢你对此的任何帮助,我现在得到的输出只是一个零时我问大小,似乎没有添加任何人,这可能是问题所在

import java.util.ArrayList;
public class Phonebook implements Directory
{

  private ArrayList<Person> book;

  public Phonebook ()
  {

    book = new ArrayList<Person>();

  }

  /**
   * will return the number of entries currently entered in
   * the <code>Directory</code>.
   * @return - the number of valid entries in the <code>Directory</code>.
   **/
  public int size()
  {
    return book.size();
  }


  /**
   * will display the entries currently entered in the <code>Directory</code>.
   **/
  public void listAll()
  {
    for(int i = 0; i < book.size(); i++)
    {
      System.out.println(book.get(i));
    }
  }


  /**
   * will add a new record to the <code>Directory</code> in alphabetical order
   * if the name is not a duplicate entry.  Otherwise no changes will be made.
   * @param name - name of individual to be added to the <code>Directory</code>.
   * @param number - phone number of the individual to be added.
   * @return - true if the entry was added successfully, otherwise false.
   **/
  public boolean addPerson(String name, String number)
  {
       Person x = new Person (name, number);
       if (checkPerson(name) == -1)
          return false;
       int index = 0;
       while(index < book.size())
       {
        if((x.getName().compareTo((book.get(index)).getName())) < 0)
        {
          book.add(x);
          return true;
        }
        index++;
       }
       return false;
   }



  public int checkPerson(String name)
  {

     int lo = 0;
     int hi = book.size() - 1;
     while(lo <= hi)
     {
       int half = (lo + hi) / 2;
       if(name.equals(book.get(half).getName()))
          return half;
       if(name.compareTo(book.get(half).getName()) < 0){
          hi = half - 1;}
       else lo = half + 1;
     }
     return -1;
  }

  /**
   * will remove an entry from the <code>Directory</code> if the name parameter
   * is currently in the <code>Directory</code>.  Otherwise no changes 
   * will be made.
   * @param name - individual to be removed from the <code>Directory</code>.
   * @return - true if the entry was successfully removed, otherwise false.
   **/
  public boolean removePerson(String name)
  {
     if (checkPerson(name) == -1)
          return false;
     book.remove(checkPerson(name));
     return true;

   }


  /**
   * will search the <code>Directory</code> to find out if the name passed in
   * is currently in the <code>Directory</code>.  If so, it will return the 
   * phone number associated with this person.  Otherwise it will return null.
   * @param name - name of individual to look up in the <code>Directory</code>.
   * @return - the phone number if the name was found, otherwise null.
   **/
  public String lookUp(String name)
  {
    Person n = new Person (name, "999-9999");
    int local = checkPerson(n.getName());
    if(local == -1)
      return null;
    return book.get(local).getNumber();

  }


  /**
   * will search the <code>Directory</code> to find out if the phone number
   * is currently in the <code>Directory</code>.  If so, it will return the 
   * name associated with this number.  Otherwise it will return null.
   * @param number - name of individual to look up in the <code>Directory</code>.
   * @return - the name of the person if the number was found, otherwise null.
   **/

  public String lookUpNum(String number)
  {
    for(int i = 0; i <book.size(); i++)
    {
      if(number.equals(book.get(i).getNumber()))
        return book.get(i).getName();
    }
      return null;
    }

  }

/ **  * Person 类是一个容纳类的容器类  *个人的姓名和电话号码。有方法  *访问名称和号码,并修改名称和号码。  *每个名称都存储在&#34; Last,First&#34;形式,以方便搜索  *和人员分类。使用私有帮助方法  *确保姓名输入&#34; First Last&#34;表格转换为  *正确的格式。  * /

public class Person implements Comparable<Person>
{
  private String first;
  private String last;
  private String name;     // Last, First
  private String number;

  /**
   * explicit constructor, will store the first and last
   * names, as well as the entire name in Last, First order
   *
   * @param na is the name of the individual
   * @param nu is the phone number of the individual
   */
  public Person(String na, String nu)
  {
    convert(na);
    number = nu;
  }

  /**
   * copy constructor, will make an exact copy of the parameter
   *
   * @param per is the <B>Person</B> to be duplicated
   */
   public Person(Person per)
  {
    first = per.first;
    last = per.last;
    name = per.name;
    number = per.number;
  }

  /**
   * accessor method to return the name of <B>this Person</B>
   *
   * @return the name of the individual in Last, First order
   */
   public String getName()
  {
    return name;
  }

  /**
   * accessor method to return the phone number of <B>this Person</B>
   *
   * @return the phone number of the individual
   */
  public String getNumber()
  {
    return number;
  }

  /**
   * modifier method to set a new name for <B>this Person</B>
   * The helper method convert() is called to handle the details
   *
   * @param the new name for the individual
   */
  public void setName(String na)
  {
    convert(na);
  }

  /**
   * modifier method to set a new phone number <B>this Person</B>
   * just in case somebody needs to enter witness protection
   *
   * @param the new phone number for the individual
   */
  public void setNumber(String num)
  {
    number = num;
  }

  /**
   * accessor method that implements the <B>Comparable interface</B> 
   * based on the name field for <B>this Person</B>
   * will return a positive number if <B>this</B> is greater than oth
   * zero if <B>this</B> is equal to oth
   * and a negative number if <B>this</B> is less than oth
   *
   * @return negative, zero, or positive int as per Comparable interface
   */
  public int compareTo(Person oth)
  {
    return name.toUpperCase().compareTo(oth.name.toUpperCase());
  }

  /**
   * accessor method to test if the instance data for <B>this Person</B>
   * is equal to the instance data for oth
   *
   * @return true if names and numbers match, false otherwise
   */
  public boolean equals(Person oth)
  {
    return name.toUpperCase().equals(oth.name.toUpperCase()) && number.equals(oth.number);
  }

  private void convert(String na)
  {
    if(na.indexOf(" ") == -1)
    {
      last = na;
      first = null;
      name = na;
    }
    else if(na.indexOf(",") != -1)
    {
      name = na;
      first = na.substring(na.indexOf(",") + 2);
      last = na.substring(na.indexOf(","));
    }
    else
    {
      first = na.substring(0, na.indexOf(" "));
      last = na.substring(na.indexOf(" ") + 1);
      name = last + ", " + first;
    }    

  }

  /**
   * accessor method to return the instance data of <B>this Person</B>
   * in a formatted String (24 character name field, followed by the number)
   *
   * @return name in Last, First order followed by the phone number
   */
  public String toString()
  {
    String local = name;
    if(name.length() < 8)
      local += "\t";
    if(name.length() < 16)
      local += "\t";
    local += "\t" + number;
    return local;
  }
} 


public class client
{
  public static void main(String[] args)
  {
    Phonebook nickBook = new Phonebook();


    nickBook.addPerson("name lastname", "321-3256");
    System.out.println();
    nickBook.listAll();
    System.out.println(nickBook.size());
  }
}

2 个答案:

答案 0 :(得分:1)

如果列表为空,则您的addPerson方法不会添加Person,因为while (0 < 0)将为false,并且不会输入循环:

   int index = 0;
   while(index < book.size())
   {
    if((x.getName().compareTo((book.get(index)).getName())) < 0)
    {
      book.add(x);
      return true;
    }
    index++;
   }

除了这个问题,book.add(x);将始终将新的Person添加到列表的末尾,这不是您想要的。您应该使用book.add(index,x),假设index是您希望添加新Person的位置。

最后,如果新的Person没有被添加到while循环中,这意味着这个Person应该是List中的最后一个Person,所以你必须在循环之后将它添加到List的末尾。 / p>

可能的实施:

  public boolean addPerson(String name, String number)
  {
       Person x = new Person (name, number);
       if (checkPerson(name) == -1)
          return false;
       int index = 0;
       while(index < book.size())
       {
        if((x.getName().compareTo((book.get(index)).getName())) < 0)
        {
          book.add(index,x);
          return true;
        }
        index++;
       }
       book.add(x); // this handles both the case of an empty List and the
                    // case in which the new Person should be the last Person
                    // on the list
       return true;
   }

答案 1 :(得分:1)

您的函数checkPerson错误。 book.size()在开头为0,hi结果为-1,这意味着它不会进入循环。除此之外,请考虑一下half变量。如果您使用此变量作为列表查询的索引,则可能会导致另一个数字而不是整数。

 public int checkPerson(String name)
 {

 int lo = 0;
 int hi = book.size() -1;
 while(lo <= hi)
 {
   int half = (lo + hi) / 2;
   if(name.equals(book.get(half).getName()))
      return half;
   if(name.compareTo(book.get(half).getName()) < 0){
      hi = half - 1;}
   else lo = half + 1;
 }
 return -1;

}