-1
我一直在試圖弄清楚爲什麼這段代碼不能工作幾個小時,而且我對ArrayList方法相當陌生。基本上,方法不起作用,我不確定爲什麼。編譯器說「無法找到方法 - 方法isLong」。isLong()方法不起作用
錯誤:
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class BookCollection
{
private ArrayList<Book> bookList;
public BookCollection() throws Exception
{
bookList = new ArrayList<Book>();
String firstLine, isbnI, authorI, areaI;
int lengthI;
Book book;
Scanner FILE, fileScan;
fileScan = new Scanner(new File("Books.txt"));
while (fileScan.hasNext())
{
firstLine = fileScan.nextLine();
FILE = new Scanner(firstLine);
isbnI = FILE.next();
authorI = FILE.next();
areaI = FILE.next();
lengthI = FILE.nextInt();
book = new Book(isbnI, authorI, areaI, lengthI);
bookList.add(book);
}
}
public void displayLongBooks()
{
System.out.println("LONG BOOKS\n\n");
for(int i = 0; i < bookList.size(); i++)
{
if (bookList.get(i).isLong())
{
return System.out.println(bookList.get(i)+"\n");
}
}
}
void displayBooksFromAuthor(String Author)
{
for (int i = 0; i < bookList.size(); i++)
{
if (bookList.get(i).author.equals(Author))
System.out.println(bookList.get(i));
}
}
void displayBooksFromArea(String Area)
{
for (int i = 0; i < bookList.size(); i++)
{
if (bookList.get(i).area.equals(Area))
System.out.println(bookList.get(i));
}
}
Book longestBook()
{
int maxId = 0;
int currMax = 0;
for(int i=0; i < bookList.size(); i++)
{
Book currBook = bookList.get(i);
if(currBook.getLength() > currMax)
{
currMax = currBook.getLength();
maxIdx = i;
}
}
return bookList.get(maxIdx);
}
}
`
isLong方法:
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
class Book
{
String isbn, author, area;
int length;
public Book(String isbn, String author, String area, int length)
{
this.isbn = isbn;
this.author = author;
this.area = area;
this.length = length;
}
boolean islong()
{
if(length >= 400)
return true;
else
return false;
}
String toString()
{
String s;
S = "[BOOK ISBN: " + this.isbn + ", AUTHOR: " + this.author + ", AREA: " + this.area + ", PAGES: " + this.length + "]\n";
return s;
}
public String getIsbn()
{
return this.isbn;
}
public String getAuthor()
{
return this.author;
}
public String getArea()
{
return this.area;
}
public int getLength()
{
return this.length;
}
}
`
主要方法:
`
import java.util.Scanner;
public class TestBookCollection
{
public static void main(String[] args) throws Exception
{
Scanner scan = new Scanner(System.in);
BookCollection testBooks = new BookCollection();
System.out.println(testBooks);
System.out.println();
testBooks.displayLongBooks();
System.out.println("\nChoose an author: ");
String author = scan.next();
testBooks.displayBooksFromAuthor(author);
System.out.println("\nChoose an area: ");
String area = scan.next();
testBooks.displayBooksFromArea(area);
}
}
`
你的方法叫做islong ...那裏沒有L。 – user3284549
Java標識符區分大小寫:你調用'isLong',但你聲明'islong'。 – Kenney
另請注意:使用布爾表達式來選擇true/false是完全多餘的 - 直接使用表達式:「return length> = 400;」 – Durandal