简体   繁体   中英

Java: How to search an arraylist for a instance variable of an object in the array

The following piece of code is giving me a massive headache. It only kind of does what I want it to do, which is take an inputted string, and then search the arraylist of book objects by the object's classification (a string) and then return that book object. Currently the code below works as long as the input classification is an actual classification of a book in the list. Eg TD999 is found so it is returned. But if I type a bunch of nonsense eg yhgfsdsfbv for the class, it still returns a book eg TD345 (seem it turns a book that was originall classed as null and then classed using the setClassification method when the programme runs.

public Book searchClass(String inputClass){
    Book foundBook = null;
    for(Book findClass : bookStore){
        if(findClass.getClassification()!=null &&
 findClass.getClassification().equalsIgnoreCase(givenClass)) 
        return findClass;
            foundBook = findClass;
    }
    return foundBook;
}

My attempt to fix it was this:

public Book searchClass(String inputClass) throws IllegalArgumentException{

    Book foundBook = null;
    for(Book findClass : bookStore){
        if(!(findClass.getClassification().equalsIgnoreCase(inputClass))){
                   throws new IllegalArgumentException("book not found")
        }
        else if(findClass.getClassification().equalsIgnoreCase(inputClass)){
            foundBook = findClass;
        }
    }
    return foundBook;
}

However this will throw the exception every single time, even if I correctly enter a classification that is in the list.

I have no idea how to fix this to do what I want, I have tired doing it numerous other ways, never works properly. I have read a through all my lecture notes, several textbooks and oracle webpages and have no idea what is causing the problem, hence I am unable to fix it.

Let's take your first attempt. If you find a book you return it immediately. Therefore, if you get through the entire loop without finding anything, you should signal failure: return null, or throw an exception. There's no point in returning foundBook because you know you didn't find anything.

That means that there's no need for a foundBook variable at all.

public Book searchClass(String inputClass) {
    for (Book book: bookStore) {
        if (book.getClassification() != null &&
            book.getClassification().equalsIgnoreCase(inputClass))
        {
            return book;
        }
    }

    throw new IllegalArgumentException("book not found");
}

Another way to write this is to use Java 8 streams. Instead of an explicit loop you can let a stream take care of looping.

public Book searchClass(String inputClass) {
    return bookStore.stream()
        .filter(book -> book.getClassification() != null)
        .filter(book -> book.getClassification().equalsIgnoreCase(inputClass))
        .findAny()
        .orElseThrow(() -> new IllegalArgumentException("book not found"));
}

The problem is that, here:

public Book searchClass(String inputClass){
    if(findClass.getClassification()!=null && findClass.getClassification().equalsIgnoreCase(givenClass)) 
    return findClass;
        foundBook = findClass;
}

If the if condition is true, then it returns the book, else, if it is not true, then it sets foundbook to findclass .

Then, in the end, you return foundbook , which will always be returned , even if no book matched.

You must do:

for(Book findClass : bookStore){
    if(findClass.getClassification()!=null && findClass.getClassification().equalsIgnoreCase(givenClass)) 
    return findClass; //return the book
}
return null; // if no book was found, then return null.

I will try to explain on code please read comment and fix your own so it will be useful to make you learn, I hope.

public Book searchClass(String inputClass) throws IllegalArgumentException{

    Book foundBook = null;
    for(Book findClass : bookStore){
       // if(!(findClass.getClassification().equalsIgnoreCase(inputClass))){
         //          throws new IllegalArgumentException("book not found")
        //}//remove these because each loop checks that 
        if(findClass.getClassification().equalsIgnoreCase(inputClass)){
            foundBook = findClass; // return findClass; // you do not need any more iteration you found it.
        }
    }
    return foundBook; //if you are here that means no match throw exception //throws new IllegalArgumentException("book not found")


}
public static int personThereAlready(String name, ArrayList<Person> people) {
    int index = -1;
    for(int i=0; i < people.size();i++) {
        Person person = people.get(i);
            
        if (person.getName().equalsIgnoreCase(name)) {
            index = i;
            break;
        }
    }
    return index;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM