【问题标题】:Constructor TextBook in class TextBook Cannot be applied to given types类 TextBook 中的构造函数 TextBook 不能应用于给定类型
【发布时间】: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。

标签: java arrays string


【解决方案1】:

您正在尝试通过调用默认构造函数来创建 TextBook 的实例。

在您的类中,您已经定义了一个构造函数,其签名需要一个字符串和一个整数。

默认构造函数是:

public TextBook() {
    // body
}

因此,要么将上面的构造函数添加到代码中,要么通过提供所需参数来正确使用现有构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多