首页 > 解决方案 > 显示搜索结果 JAVA ArrayLists

问题描述

我应该完全使用该方法(我所有的方法都必须返回 void)

public void searchByPriceRange(double minPrice, double maxPrice)

该方法将搜索ArrayList<Property>要价介于 minPrice 和 maxPrice 之间的属性,并将每个匹配项添加到本地ArrayList<Property>,然后将其传递给必须是的另一个方法

displaySearchResults(ArrayList<Property> searchResults)

我将如何创建一个ArrayList<Property>可以在第一种方法范围之外访问的本地?(如果那是我应该做的)

我的实例变量和 ArrayList 的初始化

 private ArrayList<Property> properties = new ArrayList<Property>();

我在 AgentListing 类中的方法

public void searchByPriceRange(double minPrice, double maxPrice){

    ArrayList<Property> searchResults;
    searchResults = new ArrayList<Property>();
    for (Property property : properties){
        if (property.getAskingPrice() > minPrice &&
                property.getAskingPrice() < maxPrice){


            searchResults.add(property);
           
        }
    }
}

我的显示方法 AgentListing 类

public void displaySearchResults(ArrayList<Property> searchResults){


    for(Property result: searchResults) {

        System.out.println(result);
    }

}

我试图访问本地数组列表的驱动程序类

AgentListings CharlesListings = new AgentListings();

        Property one = new Property("1ListingNumber", "777 Imaginary Drive, Nowhere, British Columbia", 1.00, "Single Family", "House",
            "1.1 Acre", 2007);

    one.setNumberOfBedrooms(1);
    one.setNumberOfBathrooms(1);


    Property two = new Property("2ListingNumber", "777 Imaginary Drive, Nowhere, British Columbia", 2.00, "Single Family", "House",
            "2.2 Acre", 2007);

    two.setNumberOfBedrooms(2);
    two.setNumberOfBathrooms(3);

CharlesListings.addProperty(one);
CharlesListings.addProperty(two);

CharlesListings.searchByPriceRange(1.0, 2.0);

CharlesListings.displaySearchResults(searchResults); //searchResults is not reachable

如果我不清楚,我会将完整的说明添加到我的作业中

标签: javaarraylist

解决方案


我将如何创建一个可在第一种方法范围之外访问的本地 ArrayList?(如果那是我应该做的)

这里:

public void searchByPriceRange(double minPrice, double maxPrice)

返回一个列表(searchResults)而不是 void...

您可以定义一个临时变量,或者只是将返回的值作为参数排队到显示方法

ArrayList<Property> x = searchByPriceRange(min, max);
displaySearchResults(x);

或者

displaySearchResults(searchByPriceRange(min, max));

推荐阅读