gpt4 book ai didi

Java从具有多个条件的列表中搜索子列表

转载 作者:行者123 更新时间:2023-11-30 09:35:59 26 4
gpt4 key购买 nike

我想从餐厅列表中创建一个搜索方法。用户有一个 GUI 表单,只填写他想要的字段。我做了一个方法 meetsCriteria 来检查这家餐厅是否存在。它有效,但并非在所有情况下都有效。

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;
}
}
}

最佳答案

首先为“meetsCriteria”方法编写单元测试,以便您可以轻松查看哪些条件通过,哪些条件失败。

例如:

assertTrue(myRestaurant.meetsCriteria("nandos", "new york", "0124536", "tasty"));

另外,我可能会把你的“searchRestaurant”改成这样:

List<Restaurant> searchRestaurant(List<Restaurant> allRestaurants, String name, String area, String phone, String category) {
List<Restaurant> matches = new ArrayList<Restaurant>();
for (Restaurant restaurant : allRestaurants) {
if (restaurant.meetsCriteria(name, area, phone, category)) {
matches.addRestaurant(allRestaurants.get(i));
}
}
return matches;
}

关于Java从具有多个条件的列表中搜索子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11019095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com