搜索地址簿以获取信息

时间:2014-03-30 18:07:09

标签: java search arraylist

我正在尝试制作一个地址簿,提示您输入三个人的第一个,最后一个,街道地址,城市,州和邮政编码。

然后能够搜索用户输入的任何信息,然后显示该人的所有信息。

我设法让它提示用户添加信息,但我似乎无法弄清楚如何搜索arraylist以获取信息。

for (int count = 0; count < 3; count++)
  {
    aBook.add(new YAAddressBook());
    aBook.get(count).addEntry();
    System.out.println();
  }

  int foundIndex = YAAddressBook.search(aBook);
  System.out.println();
  if (foundIndex > -1)
    aBook.get(foundIndex).display();
  System.out.println("Found");
  else
  System.out.println("No Entry Found");
}
}//end YoungAndrewChapter10


import java.util.ArrayList;
import java.util.Scanner;

public class YAAddressBook
{
  private static String first;
  private static String last;
  private static String choice;
  private static String searchA;
  private static Scanner keybd = new Scanner(System.in);
  private String street;
  private String cityState;
  private String zip;
  private int answer = 0;

  public static int search(ArrayList<YAAddressBook> aBook)
  {
    System.out.print("Search Menu: \n1. Search First Name \n2. Search Last
      Name\n3.Search Street Address \n4.Search City, State \n5.Search Zip Code \n\n");

     System.out.print("Please Enter Field to Search: ");
    choice = keybd.nextLine();

    System.out.print("Please Enter Value to Search For: ");
    searchA = keybd.nextLine();

    switch (choice)
    {
      case "1":
        break;
      case "2":
        break;
      case "3":
        break;
      case "4":
        break;
      case "5":
        break;
      default:
        break;
    }
    return -2;
  }

  public void addEntry()
  {
    YAAddressBook aBook = new YAAddressBook();
    System.out.print("Please Enter First Name: ");
    first = keybd.nextLine();
    System.out.print("Please Enter Last Name: ");
    last = keybd.nextLine();
    System.out.print("Please Enter Street Address: ");
    street = keybd.nextLine();
    System.out.print("Please Enter City, State: ");
    cityState = keybd.nextLine();
    System.out.print("Please Enter Zip Code: ");
    zip = keybd.nextLine();
  }
}//end YAAdreesBook

1 个答案:

答案 0 :(得分:0)

根据所选的字段,您必须遍历所有的arraylist,直到找到正确的项目,例如,如果选择了FirstName:

for (int i = 0; i< addressbook.size(); i++)
{
     if (addressbook.get(i).FirstName == "Tom" )
             return addressbook.get(i);
}
return null;

这将返回与搜索匹配的第一个元素,如果没有匹配则返回null