na2193
na2193

Reputation: 43

Searching for a book title using linked list in java

I am trying to write a program where a user can search for a book by entering the title of the book. I used linked list to store a few book. I created a method called findBook with a string parameter. When I ask the user to search for a book and run the method, it does not work, but when I input the the title of the book in the findBook method in the code, it works. Here is some of my code that doesn't work:

    book.insertBook("The Great Gatsby", "Scott Fitzgerald", 12345);
    book.insertBook("To Kill a Mockingbird", "Harper Lee", 23456);

public Library findBook(String bookName)
{
    Library theBook = firstBook;

    if(!isEmpty())
    {
        while(theBook.bookName != bookName)
        {
            if(theBook.next == null)
            {
                return null;
            }
            else
            {
                theBook = theBook.next;
            }
        }
    }
    else
    {
        System.out.println("Our Library is empty");
    }

public void searchBookTitle()
{
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Here is a list of current books we have");
    book.display();

    System.out.println("Enter the Title of the Book you would like to check out");
    String bookTitle = keyboard.nextLine();

    String findBookTitle = book.findBook(bookTitle).bookName;

    System.out.println(findBookTitle + " was found");

}

When I change the searchBookTitle method to this, it works, but I want the user to input the title:

public void searchBookTitle()
{
    String findBook = book.findBook("Of Mice and Men").bookName;
    System.out.println(findBook + " was found");
 }

Upvotes: 0

Views: 1662

Answers (2)

Pooya
Pooya

Reputation: 6136

you should compare strings by equals():

if(!isEmpty())
{
    while(!theBook.bookName.equals(bookName))
    {
        if(theBook.next == null)
        {
            return null;
        }
        else
        {
            theBook = theBook.next;
        }
    }
}
else
{
    System.out.println("Our Library is empty");
}

Upvotes: 2

Gavriel
Gavriel

Reputation: 19247

This compares the references:

while(theBook.bookName != bookName)

You need to compare the string values:

while(!theBook.bookName.equals(bookName))

It found the book when you searched for book.findBook("Of Mice and Men") because the compiler optimized it and used the same String reference. If you would've search for findBook("The " + "Great Gatsby"), then it wouldn't find it, because it would create a new String with a different reference.

Upvotes: 0

Related Questions