我想使用Book类中的方法isLong()并在BookLolBooks()中使用它,这是在BookCollection方法中。类BookCollection具有bookList变量。变量bookList是ArrayList类型,包含所有书籍的集合。 ArrayList中的所有对象都是Book类型。
import java.util.ArrayList;
public class BookCollection
{
ArrayList<Book> bookList = new ArrayList<Book>();
public BookCollection(){
bookList.add(new Book(1001-01-141514, "Letones", "CS", 611));
bookList.add(new Book(1002-01-141424, "Lewis", "CS", 477));
bookList.add(new Book(1003-01-141434, "Smith", "MATH", 698));
bookList.add(new Book(1004-01-141444, "Smith", "CS", 617));
bookList.add(new Book(1005-01-141454, "Brown", "CHEM", 326));
bookList.add(new Book(1006-01-141464, "Smith", "BIO", 127));
bookList.add(new Book(1007-01-141474, "Sanket", "CS", 998));
}
public String toString()
{
}
public void displayLongBooks()
{
System.out.println();
System.out.println("LONG BOOKS");
if (isLong() == true)
System.out.println(bookList);
}
public void displayBooksFromAuthor(String author)
{
}
public void displayBooksFromArea(String area)
{
}
public void displayAverageLength()
{
}
}
import java.util.*;
import java.io.*;
public class Book
{
String author;
String area;
int isbn;
int pages;
public Book (int isbn, String author, String area, int pages)
{
this.isbn = isbn;
this.author = author;
this.area = area;
this.pages = pages;
}
public boolean isLong()
{
if(pages>600)
return true;
else
return false;
}
public String toString()
{
return "ISBN: " + this.isbn + "Author: " + this.author
+ "Subject: " + this.area + "Pages: " + this.pages;
}
/**PrintWriter outfile = new PrintWriter (new FileWriter("books.txt"));
outfile.write("100101141514, Letones, CS, 611");
outfile.write(100201141424, Lewis, CS, 477);
outfile.write(100301141434, Smith, MATH, 698);
outfile.write(100401141444, Smith, CS, 617);
outfile.write(100501141454, Brown, CHEM, 326);
outfile.write(100601141464, Smith, BIO, 127);
outfile.write(100701141474, Sanket, CS, 998);
outfile.close();**/
}
答案 0 :(得分:2)
听起来您需要为bookList
(s)迭代Book
并为每个Book.isLong()
调用public void displayLongBooks()
{
System.out.println();
System.out.println("LONG BOOKS");
for (Book b : bookList) { // <-- for each Book b in bookList
if (b.isLong()) { // no need for == true
System.out.println(b); // <-- b, not bookList
}
}
}
。使用可能类似
for-each
loop
{{1}}