简体   繁体   English

在数组列表中搜索字符串(Java)

[英]Searching for String in array list (Java)

I created a method which searches for a string in an array list, however I the problem is, if I search for a book it has to be the exactly how it was inputted into the array list. 我创建了一种在数组列表中搜索字符串的方法,但是我的问题是,如果我要搜索一本书,它必须准确地输入到数组列表中。

eg if I type in "Harry Potter" as a book title and search for it, I have to put in "Harry Potter", I can't put "harry potter" or "HARRY POTTER"as it won't recognize it, i know there is something called ignore case but can't get it to work, or may have had it in the wrong place. 例如,如果我输入“哈利·波特”作为书名并进行搜索,则必须输入“哈利·波特”,我不能输入“哈利·波特”或“哈利·波特”,因为它无法识别,我知道有一种叫做“忽略大小写”的东西,但无法正常工作,或者可能放置在错误的位置。

My code: 我的代码:

public void searchBook() {

    System.out.println("\n"+"Enter the title of the book you would like to search for: ");
    String search = input.nextLine();

    for (int i = 0; i < newBook.size(); i++) {

        // IF statement to check that any book in the array list equals what
        // the user has typed in
        if ( newBook.get(i).getTitle().equals(search)  ) {

            System.out.println(("Book ID: " + newBook.get(i).getBookID() + "  Title: " + newBook.get(i).getTitle()
                    + "    Author: " + newBook.get(i).getAuthor() + "  Genre: " + newBook.get(i).getGenre()
                    + "   Date registered: " + newBook.get(i).getDateReg() + "   Loan Status: "
                    + newBook.get(i).getLoan() + "    Number of times loaned: " + newBook.get(i).getNumOfLoans()));

        } else {

            System.out.println("No match was found");
        }

    } // end of for

}// end of method

Change 更改

if (newBook.get(i).getTitle().equals(search)

to

if (newBook.get(i).getTitle().equalsIgnoreCase(search)

The equalsIgnoreCase performs a String comparison ignoring case. equalsIgnoreCase执行忽略大小写的字符串比较。

use equalsIgnoreCase() instead of equals() 使用equalsIgnoreCase()代替equals()

Read for documentation here 在此处阅读文档

from javadoc, 从javadoc

Compares this String to another String, ignoring case considerations. 不考虑大小写考虑,将此字符串与另一个字符串进行比较。 Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case. 如果两个字符串的长度相同,并且两个字符串中的相应字符相等,则忽略大小写。

对于搜索contains方法更正确

if (newBook.get(i).getTitle().toLowerCase().contains(search.toLowerCase()))

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

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