Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 239
  • Last Modified:

Help with constructor problem

I have the following code in Catalogue.java:

   public void addBook(String addTitle, String addAuthor, String addYear)
   {      
      array = books.length;
     
      books[array] = new Book(addTitle, addAuthor, addYear);
   }

It complains on the last line when trying to add a new book to the array.

The constructors in Book.java are:

   public void Book()
   {
     
      title = "";
      author = "";
      year = "";
     
   }
   
   
   public void Book(String aTitle, String aAuthor, String aYear)
   {
     
      title = aTitle;
      author = aAuthor;
      year = aYear;
                 
   }

Can someone tell me why this doesn't work?

thx
adam
0
AdamJSawyer
Asked:
AdamJSawyer
  • 4
  • 2
1 Solution
 
sciuriwareCommented:
Delete the word void in the constructor.

;JOOP!
0
 
sciuriwareCommented:
A constructor must return a new object, thus do not mention a type, just:  "public book(....."

;JOOP!
0
 
AdamJSawyerAuthor Commented:
The error returned by JCreator is:

--------------------Configuration: DaRock - j2sdk1.4.1 <Default> - <Default>--------------------
C:\Documents and Settings\Adam\My Documents\!DaRock\Catalogue.java:34: cannot resolve symbol
symbol  : constructor Book (java.lang.String,java.lang.String,java.lang.String)
location: class Book
      books[array] = new Book(addTitle, addAuthor, addYear);
                            ^
1 error

Process completed.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
sciuriwareCommented:
Did you delete the word 'void' in 2 constructors?

Then:

      array = books.length;
     
      books[array] = new Book(addTitle, addAuthor, addYear);

Will fail: obviously 'books' has a length of 'array', so the last index is array-1.

;JOOP!
0
 
sciuriwareCommented:
................ and heed my last remark.

;JOOP!
0
 
AdamJSawyerAuthor Commented:
sorry for lack of feedback. Yeah I fixed those constructors and then fiddled the code to work. the guy I was helping was new to programming and wasn't sure about arrays. I set the array to a predetermined size with a constant, and used an index to point to the place the next book was to be created. Thanks for you help

Cheers
Adam
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now