【发布时间】:2019-11-12 21:46:32
【问题描述】:
我有一个项目要我创建 3 个类:TextBook、LibraryCard 和 Library,我需要将 TextBook 对象放入 bookshelf 数组;我已经创建了前 2 个并且它们工作正常,但是,库类给了我这个错误:
Constructor TextBook in class TextBook cannot be applied to given types;
Required: java.lang.string
Found: no arguments
reason: actual and formal argument lists differ in length
这是教科书类的代码:
public class TextBook
{
private String Title;
private int Chapters;
private int LastChapter;
/**
* Constructor for objects of class TextBook
*/
public TextBook(String Titlename, int Chapters_init)
{
// initialise instance variables
Title = Titlename;
Chapters = Chapters_init;
LastChapter = 0;
}
public String getTitle()
{
return Title;
}
public void readNextChapter()
{
for(LastChapter=0;LastChapter<Chapters;LastChapter++) {
System.out.println("You have finished the book!");
}
}
public boolean isfinished()
{
if (LastChapter == Chapters)
return true;
else
return false;
}
public void closeBook()
{
LastChapter = 0;
}
public void describe()
{
System.out.println("You are currently Reading " + Title);
}
这是库类的代码:
public class Library
{
int nextBook;
int borrowers = 0;
public Library(int Max_Books)
{
TextBook[] bookshelf = new TextBook[5];
for(int ptr=0;ptr<bookshelf.length;ptr++)
bookshelf[ptr] = new TextBook();
}
提前谢谢你。
【问题讨论】:
-
这个错误有什么令人困惑的地方?你调用
new TextBook()但构造函数需要一个字符串和一个 int -
TextBook的构造函数定义为public TextBook(String Titlename, int Chapters_init)。这意味着你必须这样称呼它new TextBook("Book title goes here", 25);。如果你不带参数调用它,像这样new TextBook(),你会得到你描述的错误。如果你想实例化一个没有标题和章节数的构造函数,你可以添加一个无参数构造函数。 -
哦,非常感谢您的帮助,对不起,我刚接触 java。