How can i print a void method that iterates through a LinkedList

I’m creating a class that monitors the price, address and number of bedrooms within a house. I’m trying to call the result for my twoBeds method. Pretty sure my Sysout is completely wrong but I dont know where to start.

public class House {

    int price;
    int bedrooms;
    String address;

    public House(int a, int b, String c) {
        price = a;
        bedrooms = b;
        address = c;
    }

    static List<House> agency = new LinkedList<House>();

    public static int noHouse() {
        return agency.size();
    }

    public static void twoBeds() {
        for (ListIterator<House> it = agency.listIterator(); it.hasNext(); ) {
            House h = it.next();
            if (h.bedrooms == 2) {
                System.out.println(h.address);
            }
        }
    }

    public static void main(String[] args) {
        House h1 = new House(12, 2, "address");
        agency.add(h1);
        System.out.println(twoBeds());
    }
}

Answer

System.out.println() accepts a parameter, void return type means that there is nothing to return.

You need to return something to print it.

Option 1: Do not pass void function in System.out:

public static void main(String[] args) {
    House h1 = new House(12, 2, "address");
    agency.add(h1);
    twoBeds();
}

Option 2: Change return type of twoBeds():

public static List<String> twoBeds() {
    List<String> matchedAddresses = new ArrayList<>();
    for (ListIterator<House> it = agency.listIterator(); it.hasNext(); ) {
        House h = it.next();
        if (h.bedrooms == 2) {
            matchedAddresses.add(h.address);
        }
    }
    return matchedAddresses;
}

Leave a Reply

Your email address will not be published. Required fields are marked *