americanheartbreak americanheartbreak - 1 month ago 8
Java Question

java source code class

Can anyone help to advise what I am doing wrong. I am trying to search a class for objects by year but if there are no matches I want a statement to print out that there are no matches but its not working it just is printing out even if the year is found. Thanks in advance for help

//search by year

public void searchByYear(int year){
for(Book s : books){
if(s.getYear()==year){
System.out.println(s.toString());
}
}System.out.println("No match");
}

Answer

An alternate solution:

final List<Book> matches = new ArrayList<>();
for (Book s : books) {
    if (s.getYear() == year) {
        matches.add(s);
    }
}

if (matches.isEmpty()) {
    System.out.println("No match");
} else {
    for (Book s : matches) {
        System.out.println(s.toString());
    }
}