我想从餐厅列表中创建搜索方法。用户有一个 GUI 表单并且只填写他想要的字段。我做了一个方法 meetCriteria 来检查这家餐厅是否存在。它有效,但并非在所有情况下都有效。
public class RestaurantList {
private ArrayList<Restaurant> _restaurants = new ArrayList<Restaurant>();
RestaurantList selRest;
RestaurantList searchRestaurant(String name, String area, String phone, String category)
{
selRest = new RestaurantList();
for (int i=0; i< _restaurants.size(); i++)
{
if(_restaurants.get(i).meetsCriteria(name, area, phone, category))
{
selRest.addRestaurant(_restaurants.get(i));
}
}
return this.selRest;
}
public class Controller {
//this is list with all Restaurants
static RestaurantList restList = new RestaurantList();
//this is list with the result of the search.
public static RestaurantList selList; // selectedList
public void addRestaurant (Restaurant rest)
{
restList.addRestaurant(rest);
}
public void searchCriteria(String name, String area, String phone, String category)
{
int size = restList.getRestaurants().size();
for(int i =0; i<size; i++)
selList = restList.searchRestaurant(name, area, phone, category);
}
}
public class Restaurant {
private String _name;
private String _address;
private String _phoneNum;
private Area _area;
public boolean meetsCriteria(String name, String area, String phone, String category)
{
if( this._name.equals(name) && this._area.getArea().equals(area) && this._phoneNum.equals(phone) && this._category.equals(category) )
{
return true;
}
if ( name.equals("") && area.equals(this._area.getArea()) && phone.equals("") && category.equals("") )
{
return true;
}
if ( name.equals("") && area.equals(this._area.getArea()) && phone.equals(this._phoneNum) && category.equals("") )
{
return true;
}
if (name.equals("") && area.equals(this._area.getArea()) && phone.equals("") && category.equals(this._category) )
{
return true;
}
if ( area.equals(this._area.getArea()) && phone.equals("") && category.equals("") )
{
int index = this._name.indexOf(name);
if (index != -1)
{
return true;
}else return false;
}
if (area.equals(this._area) && category.equals(this._category) )
{
return true;
}
else
{
return false;
}
}
}