PDA

View Full Version : Retriving a object from a array in readable format


Mutley
02-08-2009, 11:41 PM
Hi im trying to get a better grip on contructors and proper OOP and i have been started putting together a simple address book.

I have a Contact class that i use as a type. Sets 'name' 'phone' and 'sex'

this info is then collected form the command line and added to a ArrayList. It seems to do this fine but when retiving the data by a simple for loop that gets each object and does a tosting then prints, it just returns the memory address. Contact@9304b1

Here is my code:
AddressBookapp

public class AddressBookapp {
public static void main (String args[]){
AddressBook okk= new AddressBook();
Contact con = new Contact();
con.readIn();
okk.add(con);
System.out.println(con.getName());
okk.printall();

}
}

AddressBook

import java.util.ArrayList;
public class AddressBook {
public static ArrayList<Contact> contacts = new ArrayList<Contact>();

public AddressBook(){
contacts = new ArrayList<Contact>(20);
}
public void add(Contact con){
contacts.add(con);
}
public void printall(){
for (Contact c:contacts)
{
System.out.println(c.toString());
}
}
}

Contact

public class Contact {
private String name;
private int phoneNo;
private boolean sex;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(int phoneNo) {
this.phoneNo = phoneNo;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public boolean isSex() {
return sex;
}
public Contact(){
name ="unknown";
}
public Contact (final String n, final int p, final boolean s){
this.name = n;
phoneNo= p;
setSex(s);
}
public void readIn() {
name = Keyboard.readString();
phoneNo= Keyboard.readInt();
sex = Keyboard.readBoolean();
}
}


Sorry for what is no doubt a stupid question.

Thanks for reading

Alex

bacterozoid
02-08-2009, 11:47 PM
I assume this is the line in question:


System.out.println(c.toString());

What happens is that your object does not implement the toString() method. When you call .toString(), it's using the built-in toString() method of the object superclass.

Try adding this method to your contact class:

@Override
public String toString() {
return this.name + ", " + this.phoneNo;
}

You should also consider making phoneNo a string so you can include the "-" or "(" or ")" characters in your phone numbers...the same thing for sex, so you can use Male or Female.

Good luck!

Mutley
02-09-2009, 12:04 AM
Thanks. I had a feeling i had to edit the output but wasn't sure how.

Adding to your rep.