Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

java - The constructor is undefined in a simple exercice

I just started learning java without any prior knowledge about programming. I run into an error whe I do a simple exercice.

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);
}
}    

It says my constructor is undefined so I looked a bit and I can't quite get what mistake(s) I'm making.

Thanks in advance for the help !

question from:https://stackoverflow.com/questions/65641279/the-constructor-is-undefined-in-a-simple-exercice

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is because the paramters that your constructor expecting and what you're passing throw. You had build a constructor with 4 arguments and you're providing only 3 in his creation. You must give it 4 our build a new constructor with 3 paramters, without the publisher in that case.

The correct will be:

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

E.g:

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

Will work as well if you create a new constructor, like:

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...