QUOTE(NiekieM @ 17 Apr, 2008 - 08:09 AM)

Hi I am new to Java.I cant seem to figure it out.Not sure what I'm doing wrong.I have to write a program using arrayLists to maintain a phone book.The interface includes 4 buttons.An add, delete, update and find button.What in particular I have a problem with is to reference the nameList with the corresponding phoneList.I don't know how to get the index number.
Can anyone shed some light on the matter.Thanx!
2 little mistakes
First one: 0 is a valid index so:
CODE
public int getIndex()
{
int index=0;
if(validName())
{
for(int i = 0;i<nameList.size();i++)
{
if(nameField.getText().equals(nameList.get(i)))
index = i;
}
}
else
{
JOptionPane.showMessageDialog(null,"The list does not contain the name "+nameField.getText(),"Info",JOptionPane.INFORMATION_MESSAGE);
}
return index;
}
If name is invalid or not found will return 0 which is a valid index.
Don't really sure you need to scan 2 times the ArrayList to find if the name is in it
I mean the code of the contains() method of ArrayList much look a lot like yours. It will scan the ArrayList to find if name is on it. So I would get ride of validName and do it that way:
java
public int getIndex()
{
for(int i = 0;i<nameList.size();i++)
{
if(nameField.getText().equals(nameList.get(i)))
return i;
}
JOptionPane.showMessageDialog(null,"The list does not contain the name "+nameField.getText(),"Info",JOptionPane.INFORMATION_MESSAGE);
return -1;
}
Note that I return -1 which is not a valid index.
Your actionPerformed method will have to check if getIndex() returns -1
if it is the case just exit.
Second mistake:
CODE
public void actionPerformed(ActionEvent e)
{
index = 0;
boolean nameAdded;
boolean phoneAdded;
name = new String (nameField.getText());
phone = new String (phoneField.getText());
nameList = new ArrayList(index);
phoneList = new ArrayList(index);
So everytime actionPerformed() is called you are creating 2 NEW EMPTY ArrayList in nameList and phoneList
So remove these 2 lines:
nameList = new ArrayList(index);
phoneList = new ArrayList(index);
And your code should work... but don't forget to initialize nameList and phoneList somewhere else like
CODE
public class PhoneBook extends JFrame implements ActionListener
{
ArrayList nameList = new ArrayList();
ArrayList phoneList = new ArrayList();
String name;
String phone;
Happy coding