我有一个名为Book的课程:
public class Book {
private String title;
private boolean borrowed;
public Book(String bookTitle) {
// Store name of book and mark as not borrowed
title = bookTitle;
borrowed = false;
}
public void borrowed(){
// Set borrowed to true
borrowed = true;
}
public void returned() {
// Set borrowed to false
borrowed = false;
}
public boolean isBorrowed() {
// Return borrowed
return borrowed;
}
public String getTitle() {
// return title;
return title;
}
}
一个名为Library的课程:
public class Library {
private String address;
private ArrayList<Book> books = new ArrayList<Book>();
public Library(String Address) {
address = Address;
}
private void addBook(Book book) {
books.add(book);
}
private void borrowBook(String title) {
boolean bookFound = false;
// Find Book
}
我需要完成borrowBook方法,它将搜索数组列表以查找该书是否在库中,然后使用book类的borrowed()方法将该书标记为已租用。
到目前为止,我有类似的东西,虽然我正在努力调用借用的方法或getTitle方法,以便能够对数组列表中包含的特定book对象进行操作
for (int i = 0; i < books.size(); i++) {
if (books[i].getTitle() = title) {
books[i].borrowed();
}
}
答案 0 :(得分:0)
您的逻辑检查应为
books[i].getTitle().equals(title)
或者说
title.equals(books[i].getTitle())
。
你没有正确比较两个字符串
还要考虑其中一个或两个都是null
的情况。
答案 1 :(得分:0)
for (int i = 0; i < books.size(); i++) {
if (books.get(i).getTitle().equals(title)) {
books.get(i).borrowed();
}
}
检查(分配)
的问题if (books[i].getTitle() = title)
应替换为(比较)
if (books.get(i).getTitle().equals(title))
让它变得更好
private void borrowBook(String title) {
boolean bookFound = false;
// Find Book
for(Book book : books)
{
if (book.getTitle().equals(title))
{
bookFound = true;
book.borrowed();
break;
}
}
//...More stuffs you may want to do
}
答案 2 :(得分:0)
到目前为止,您所拥有的内容甚至无法使用索引oberator []
来访问ArrayList的元素。您需要使用列表的List#get(index)。另外,对于使用等于运算符的字符串进行比较,这是不正确的,它只能在多数情况下对不同的字符串实例不相同(除非实例化)。您需要使用String#equals(otherString)或String#equalsIgnoreCase(otherString)方法。
for (int i = 0; i < books.size(); i++) {
if (books.get(i).getTitle().equals(title)) {
books.get(i).borrowed();
}
}
您还可以使用增强型for循环
for (Book book : books) {
if (book.getTitle().equals(title)) {
book.borrowed();
}
}
答案 3 :(得分:0)
首先,您在if
语句中的签入错误,即if (books[i].getTitle() = title)
应替换为,
if(books.get(i).getTitle().equals(title))
并且在调用borrowed
函数之前不要忘记检查borrowed()
标志。
所以你的最终代码应该是,
for (int i = 0; i < books.size(); i++)
{
if (books.get(i).getTitle().equals(title))
{
if(!books.get(i).isBorrowed())
books.get(i).borrowed();
else
{
//Inform user book already borrowed
}
break;
}
}