class Library {
String libraryName;
String address;
Library(String namelibrary)
{
libraryName=namelibrary;
}
Book[] books=new Book[150];
void addBook(Book newBook)
{
books[i]= newBook;
i++;
}
class Book
{
String title;
boolean borrowed;
}
}
public class test{
public static void main(String[] args)
{
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
firstLibrary.books[0]= new Book("Maths");
}
}
当我运行此代码时,我收到无法找到符号Book的消息。
但是根据我(周)的理解,这个错误不应该出现,因为Book是Library中的类,我从它的对象中定义它 请帮忙指导。提前感谢您的帮助
答案 0 :(得分:2)
您的图书班级是Library
的成员。所以你只能通过Library类访问它。所以你的代码应该是
firstLibrary.books[0]= firstLibrary.new Book("Maths");
然后您的下一个错误是您没有适当的Book构造函数接收名称。有一个,它应该没问题。
class Book {
String title;
boolean borrowed;
public Book(String title) {
this.title = title;
}
}
好的,看起来在这个方法中还有一个错误
void addBook(Book newBook) {
books[i] = newBook;
i++;
}
你从未宣布过你的我。请声明并初始化。
class Library {
String libraryName;
String address;
private int i = 0;
..
..
看起来你最近刚开始使用Java。所以现在就避免使用嵌套类。
答案 1 :(得分:-2)
尝试在类库之后定义类书,如
class Library {
class Book{
String title;
boolean borrowed;
}
String libraryName;
String address;
Library(String namelibrary)
{
libraryName=namelibrary;
}
Book[] books=new Book[150];
void addBook(Book newBook)
{
books[i]= newBook;
i++;
}
}
public class test{
public static void main(String[] args)
{
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
firstLibrary.books[0]= new Book("Maths");
}}