I am trying to write a method that accepts the array of houses and a price, priceLimit. The method will return an array
of houses for the houses whose price is less than or equal to priceLimit. I want to make a pass
over the data to determine how big to make the return array. The problem is that I can not figure out how to add House objects from one House array to the other.

private static House[] getLowPriced(House[] houses, double priceLimit) 
{

    House[] lowPriceHouses = null;

    for (int i = 0; i <= houses.length; i++)
    {
        double prices = houses[i].getPrice();
        if (prices <= priceLimit)
            lowPriceHouses[i] = houses[i];
    }

    return lowPriceHouses;  
}

Recommended Answers

All 3 Replies

first you need to calculate the number of low price houses

int count=0;
for(int i=0;i<=houses.length;i++) {
    if(houses[i].getPrice()<=priceLimit)
        count++;
}

then initialize the lowPriceHouses array

House[] lowPriceHouses=new House[count];

then, you can store the references of low price houses in the lowPriceHouse array

int index=0;
for(int i=0;i<=houses.length;i++) {
    if(houses[i].getPrice()<=priceLimit)
        lowPriceHouses[index++]=houses[i];
}

then, return the lowPriceHouses from the function

return lowPriceHouses;

either that, or use a collection, which later on you transform to an array.
since you have no idea how many of the houses are lower than that price, you don't know the size you should set for it, all you know is the maximum possible amount.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.