简体   繁体   English

Java:如何在数组列表中搜索数组中对象的实例变量

[英]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.例如,找到了 TD999,因此将其返回。 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.但是,如果我为该类键入一堆废话,例如 yhgfsdsfbv,它仍然返回一本书,例如 TD345(似乎它变成了一本最初归类为 null 然后在程序运行时使用 setClassification 方法归类的书。

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.我已经通读了我所有的讲义、几本教科书和 oracle 网页,但不知道是什么导致了问题,因此我无法修复它。

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.返回foundBook是没有意义的,因为你知道你没有找到任何东西。

That means that there's no need for a foundBook variable at all.这意味着根本不需要foundBook变量。

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.另一种编写它的方法是使用 Java 8 流。 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 .如果 if 条件为真,则返回书,否则,如果条件不为真,则将foundbook设置为findclass

Then, in the end, you return foundbook , which will always be returned , even if no book matched.然后,最后,您返回foundbook ,即使没有匹配的书,它也将始终返回

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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