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.