Welcome to Dream.In.Code
Become a Java Expert!

Join 150,429 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,080 people online right now. Registration is fast and FREE... Join Now!




Maintaining a Phone Book with ArrayLists

 
Reply to this topicStart new topic

Maintaining a Phone Book with ArrayLists

NiekieM
17 Apr, 2008 - 07:09 AM
Post #1

New D.I.C Head
*

Joined: 6 Feb, 2008
Posts: 23

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!

Here is my code:
CODE


/*
    Chapter 9:    Maintaining a Phone Book with ArrayLists
    Date:          11 April 2008
    Purpose:    This program uses arraylists to maintain a phone book
*/

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class PhoneBook extends JFrame implements ActionListener
{
    ArrayList nameList;
    ArrayList phoneList;
    String name;
    String phone;
    double phoneNum;
    int index;

    JPanel northPanel  = new JPanel();
    JPanel centerPanel = new JPanel();
    JPanel southPanel  = new JPanel();

    JLabel nameLabel     = new JLabel("Name");
    JTextField nameField = new JTextField(20);

    JLabel phoneLabel     = new JLabel("Phone");
    JTextField phoneField = new JTextField(20);

    JButton addBttn    = new JButton("Add");
    JButton deleteBttn = new JButton("Delete");
    JButton updateBttn = new JButton("Update");
    JButton findBttn   = new JButton("Find");


    public PhoneBook()
    {
        super ("Phone Book");

        Container c = getContentPane();
        c.setLayout(new BorderLayout());

        northPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        southPanel.setLayout(new FlowLayout());

        northPanel.add(nameLabel);
        northPanel.add(nameField);

        centerPanel.add(phoneLabel);
        centerPanel.add(phoneField);

        southPanel.add(addBttn);
        southPanel.add(deleteBttn);
        southPanel.add(updateBttn);
        southPanel.add(findBttn);

        c.add(northPanel,BorderLayout.NORTH);
        c.add(centerPanel,BorderLayout.CENTER);
        c.add(southPanel,BorderLayout.SOUTH);

        addBttn.addActionListener(this);
        deleteBttn.addActionListener(this);
        updateBttn.addActionListener(this);
        findBttn.addActionListener(this);
    }

    public static void main(String[] args)
    {
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
        }

        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null,"The UIManager couldn't setthe motif look and feel","Error",JOptionPane.ERROR_MESSAGE);
        }

        PhoneBook f = new PhoneBook();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300,140);
        f.setLocation(350,350);
        f.setVisible(true);
    }

    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);


        if(e.getSource() == addBttn)
        {
            nameAdded = nameList.add(name);
            phoneAdded = phoneList.add(phone);
            if(nameList.contains(name))
            {
                JOptionPane.showMessageDialog(null,"The name "+name+" and the phone number "+phone+"  was successfully added","Info",JOptionPane.INFORMATION_MESSAGE);

                clear();

            }
        }

        if(e.getSource() == deleteBttn)
        {
            if(validName())
            {
                int phoneIndex = getIndex();
                nameList.remove(phoneIndex);
                phoneList.remove(phoneIndex);
            }


            {
                JOptionPane.showMessageDialog(null,"The name "+nameField.getText()+" was successfully removed ","Info",JOptionPane.INFORMATION_MESSAGE);
                clear();
            }
        }

        if(e.getSource() == updateBttn)
        {
        }

        if(e.getSource() == findBttn)
        {
            int findIndex = getIndex();

            phoneField.setText((String)phoneList.get(findIndex));
        }
    }

    public void clear()
    {
        nameField.setText("");
        phoneField.setText("");
        nameField.requestFocus();
    }

    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;
    }

    public boolean validName()
    {
        boolean validName = false;
        if(nameList.contains(nameField.getText()))

        validName = true;
        return validName;
    }
}


User is offlineProfile CardPM
+Quote Post

pbl
RE: Maintaining A Phone Book With ArrayLists
17 Apr, 2008 - 08:41 AM
Post #2

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,594



Thanked: 233 times
Dream Kudos: 75
My Contributions
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
User is online!Profile CardPM
+Quote Post

m2s87
RE: Maintaining A Phone Book With ArrayLists
17 Apr, 2008 - 09:16 AM
Post #3

D.I.C Regular
Group Icon

Joined: 28 Nov, 2006
Posts: 390



Thanked: 3 times
Dream Kudos: 1225
My Contributions
Assuming you need to use arraylista and do not want to use classes, for cycles(with iterators) and implement a sorting algorithm, the my guess would be, that the whole data can be stored in:
CODE

        ArrayList<String> name = new ArrayList<String>();
        ArrayList<ArrayList<String>> phone = new ArrayList<ArrayList<String>>();
        HashMap<String,ArrayList<String>> phonebook_n = new HashMap<String,ArrayList<String>>();

Well this is in the case, when one name can have several phone numbers. If one name could only have one phone number the data could be stored in:
CODE

        ArrayList<String> name = new ArrayList<String>();
        ArrayList<String> phone = new ArrayList<String>();
        HashMap<String,String> phonebook_1 = new HashMap<String,String>();

Of course if thy are new concepts, and you have no idea how to use them, you do not have to.
User is offlineProfile CardPM
+Quote Post

NiekieM
RE: Maintaining A Phone Book With ArrayLists
18 Apr, 2008 - 01:09 AM
Post #4

New D.I.C Head
*

Joined: 6 Feb, 2008
Posts: 23

Thanx a lot guys, you are life savers!!

NiekieM

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 08:51PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month