我正在尝试编写一个程序,用户可以在其中通过输入书名来搜索书籍。我使用链表来存储几本书。我创建了一个名为 findBook 的方法,其中包含一个字符串参数。当我要求用户搜索一本书并运行该方法时,它不起作用,但是当我在代码的findBook方法中输入书名时,它起作用了。这是我的一些代码不起作用:
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");
}
当我将 searchBookTitle 方法更改为此方法时,它可以工作,但我希望用户输入标题:
public void searchBookTitle()
{
String findBook = book.findBook("Of Mice and Men").bookName;
System.out.println(findBook + " was found");
}
按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");
}
这会比较引用:
while(theBook.bookName != bookName)
您需要比较字符串值:
while(!theBook.bookName.equals(bookName))
当您搜索book.findBook("Of Mice and Men")
时,它找到了这本书,因为编译器对其进行了优化并使用相同的字符串引用。如果你搜索findBook("The " + "Great Gatsby"),那么它找不到它,因为它会创建一个具有不同引用的新字符串。