• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating an Array of Objects in a Constructor  RSS feed

 
Greenhorn
Posts: 5
Firefox Browser Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all

I want to create a simple app that takes a name from the console then compares the name to a small phone book,when the name matches another name it will return the associated phone number.

I have a small contacts class which has name and number fields,Then I have a phone book class which populates an array with 4 contact objects that I can compare the entered number against.

here is my contacts class




and here is my attempt at the phonebook class



In the main method I am just trying to print out one of the fields for one contact to see if I can actually access it to compare it to the name entered.Its saying "MaryJones" cannot be resolved to a type.I'm guessing I cant create all that code in the constructor?Can anyone give me a hand on how it should look?
Thanks in advance

 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alan Flynn wrote:Can anyone give me a hand on how it should look?

Sure. Try this as a start:(I'll leave you to fill in the rest)
I think you'll find that works a lot better.

Now, the question is why?

Perhaps you can tell us?

Winston
 
Alan Flynn
Greenhorn
Posts: 5
Firefox Browser Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Winston Thanks for the quick reply!

I definitely want to try and fill it out myself!Its the only way I will learn

OK so from what I see you moved the creation of the contactList out of the Constructor?
Hmm..So does this mean the array will be created first then populated by the constructor after??
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alan Flynn wrote:OK so from what I see you moved the creation of the contactList out of the Constructor?
Hmm..So does this mean the array will be created first then populated by the constructor after??

No, it means that it is now part of the object; not part of the constructor. And that means that it can be accessed by any method IN the object.

You're worrying too much about mechanics at the moment.

Winston
 
Ranch Hand
Posts: 140
2
Java Mac
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following on from that, can you think of a way to access the name of MaryJane without declaring and initialising the variable in the class scope? If you think about what you are doing in the constructor and the affect of the change Winston suggested I think you should be able to come up with the solution. Let us know how you get on.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!