First a comment: Be careful adding "print" statements inside of classes methods. They tend not to be exactly what you want. You may come back and use the class later and be very confused at why it is printing.
There is a better solution though and it has to do with why you're seeing the strange message when printing your class.
The reason you're seeing this
workbook.Contact@46e5590e is because
Java interprets any custom class made into a
String as a <class name>@<memory address> type of format. You can override this basic behavior relatively easily in
To do this simply override (create) the
toString() method in your class. Java will automatically call this when printing or combining with other strings.
Everything that follows from this is going to assume that you've created the
toString() method as I did above...
Then when you want to print out the contact you can simple do this:
This will print out the expected contact.
It is also helpful to do this because you might want to combine it with other strings/formats:
Conrado Sanchez wrote:The number of Contact that I input is just one when I run the program so the Number of contacts: 1 is correct, but it gives me workbook.Contact@46e5590e instead of printing out all the contacts stored inside the Contact class. Yes I do loop through the ArrayList and I also have a method inside the Contact class, the printNameAndPhone(), which prints out the name as well as the phone number but how do I incorporate the printNameAndPhone() method (located in the Contact class) inside the print() method (located inside the AddressBook class)???
Basically I'm asking how to access all the elements in the ArrayList<Contact> addressBook = new ArrayList<>();??
So you can use my above method, It will print out the
addressBook as a list of contacts:
This is currently what you're doing. If you'd like to control how it prints more you could simple loop through the
addressBook (since its a list after all)
But once again there is a better solution here I think. But this requires a bit more work on your overall program design. Which would be more in depth and may be overkill for a simple problem (if you're just trying to solve a simple problem and not trying to design an actual system).