java—构造函数在简单的练习中未定义

wi3ka0sx  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(354)

我刚开始学习java,之前对编程一无所知。我做一个简单的练习时遇到了一个错误。

public class Book{

    String title;

    String author;

    int numberOfPages;

    String publisher;

public Book (String titleBook, String authorBook, int pagesBook, String publisherBook){

    title = titleBook;
    author = authorBook;
    numberOfPages = pagesBook;
    publisher = publisherBook;

}  
public static void main (String[] args){

    Book myBook = new Book ("Seeker","Jack McDevitt",368);
    System.out.println(myBook);
}
}

它说我的构造函数是未定义的,所以我看了一点,我不太明白我犯了什么错误。
提前感谢您的帮助!

zz2j4svz

zz2j4svz1#

这个问题是因为构造函数期望的参数和传递的参数抛出了。你用4个参数构建了一个构造函数,而在他的创建过程中你只提供了3个参数。你必须给它4我们建立一个新的构造函数与3个参数,没有出版商在这种情况下。
正确答案是:

Book myBook = new Book ("Seeker","Jack McDevitt",368, "publisher");

例如:

Book myBook = new Book ("Seeker","Jack McDevitt",368, "Polaris");

如果您创建一个新的构造函数,也能正常工作,如:

public Book (String titleBook, String authorBook, int pagesBook)
    title = titleBook;
    author = authorBook;
    numberOfPages = pagesBook;
    publisher = null; //In that case, you need to set null here

}

相关问题