473,554 Members | 2,950 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Phone directory remove directory

55 New Member
I am trying to write a code for a Phone Directory program. This program is suppose to allow the user to enter a name or directory and then program can either add, save or even delete an entry. Also this program has more then one class and also uses an interface. Right now I am working on
ArrayBasedPD class. I am trying to write a code for the remove method (line 158) that allows the user to enter a name, once the program sees that the name is in the directory, it deletes it. The way I tried to do it was simply do the opposite of the Add method, instead of incrementing the size of the array, I would decrement it, because I would believe that when decrementing the size that an entry is being deleted.
This may be kinda confusinf to understand since their are more Classes for this program, such as the Class phone directory is an interface that is being implemented by theArrayBasedPD class (this one).

Expand|Select|Wrap|Line Numbers
  1. package CH01;
  3. import java.io.*;
  5.  /** This is an implementation of the PhoneDirectory interface that uses
  6.   *   an array to store the data.
  7.   *   @author Koffman & Wolfgang
  8.   */
  10. public class ArrayBasedPD implements PhoneDirectory {
  12.   // Data Fields
  14.   /** The initial capacity of the array */
  15.   private static final int INITIAL_CAPACITY = 100;
  17.   /** The current capacity of the array */
  18.   private int capacity = INITIAL_CAPACITY;
  20.   /** The current size of the array (number of directory entries) */
  21.   private int size = 0;
  23.   /** The array to contain the directory data */
  24.   private DirectoryEntry[] theDirectory =
  25.       new DirectoryEntry[capacity];
  27.   /** The data file that contains the directory data */
  28.   private String sourceName = null;
  30.   /** Boolean flag to indicate whether the directory was
  31.       modified since it was either loaded or saved. */
  32.   private boolean modified = false;
  34.   /** Method to load the data file.
  35.        pre:  The directory storage has been created and it is empty.
  36.         If the file exists, it consists of name-number pairs
  37.         on adjacent lines.
  38.        post: The data from the file is loaded into the directory.
  39.        @param sourceName The name of the data file
  40.    */
  41.   public void loadData(String sourceName) {
  42.     // Remember the source name.
  43.     this.sourceName = sourceName;
  44.     try {
  45.       // Create a BufferedReader for the file.
  46.       BufferedReader in = new BufferedReader(
  47.           new FileReader(sourceName));
  48.       String name;
  49.       String number;
  51.       // Read each name and number and add the entry to the array.
  52.       while ( (name = in.readLine()) != null) {
  53.         // Read name and number from successive lines.
  54.         if ( (number = in.readLine()) == null) {
  55.           break; // No number read, exit loop.
  56.         }
  57.         // Add an entry for this name and number.
  58.         add(name, number);
  59.       }
  61.       // Close the file.
  62.       in.close();
  63.     }
  64.     catch (FileNotFoundException ex) {
  65.       // Do nothing — no data to load.
  66.       return;
  67.     }
  68.     catch (IOException ex) {
  69.       System.err.println("Load of directory failed.");
  70.       ex.printStackTrace();
  71.       System.exit(1);
  72.     }
  73.   }
  75.   /** Add an entry or change an existing entry.
  76.       @param name The name of the person being added or changed
  77.       @param number The new number to be assigned
  78.       @return The old number or, if a new entry, null
  79.    */
  80.   public String addOrChangeEntry(String name, String number) {
  81.     String oldNumber = null;
  82.     int index = find(name);
  83.     if (index > -1) {
  84.       oldNumber = theDirectory[index].getNumber();
  85.       theDirectory[index].setNumber(number);
  86.     }
  87.     else {
  88.       add(name, number);
  89.     }
  90.     modified = true;
  91.     return oldNumber;
  92.   }
  94.   /** Look up an entry.
  95.     @param name The name of the person
  96.     @return The number. If not in the directory, null is returned
  97.    */
  98.   public String lookupEntry(String name) {
  99.     int index = find(name);
  100.     if (index > -1) {
  101.       return theDirectory[index].getNumber();
  102.     }
  103.     else {
  104.       return null;
  105.     }
  106.   }
  108.   /** Method to save the directory.
  109.       pre:  The directory has been loaded with data.
  110.       post: Contents of directory written back to the file in the
  111.             form of name-number pairs on adjacent lines.
  112.             modified is reset to false.
  113.    */
  114.   public void save() {
  115.     if (modified) { // If not modified, do nothing.
  116.       try {
  117.         // Create PrintWriter for the file.
  118.         PrintWriter out = new PrintWriter(
  119.             new FileWriter(sourceName));
  121.         // Write each directory entry to the file.
  122.         for (int i = 0; i < size; i++) {
  123.           // Write the name.
  124.           out.println(theDirectory[i].getName());
  125.           // Write the number.
  126.           out.println(theDirectory[i].getNumber());
  127.         }
  129.         // Close the file and reset modified.
  130.         out.close();
  131.         modified = false;
  132.       }
  133.       catch (Exception ex) {
  134.         System.err.println("Save of directory failed");
  135.         ex.printStackTrace();
  136.         System.exit(1);
  137.       }
  138.     }
  139.   }
  141.   /** Find an entry in the directory.
  142.       @param name The name to be found
  143.       @return The index of the entry with the requested name.
  144.               If the name is not in the directory, returns -1
  145.    */
  146.   private int find(String name) {
  147.     for (int i = 0; i < size; i++) {
  148.       if (theDirectory[i].getName().equals(name)) {
  149.         return i;
  150.       }
  151.     }
  152.     return -1; // Name not found.
  153.   }
  154.   /**remove Entry
  155.    * @param name The name of the person to be deleted
  156.    * 
  157.    */
  158.      public void remove(String name) {
  159.      int i = find(name);
  160.       if(i <= -1)
  161.      System.out.println("Entry not found; cannot delete!");
  162.      else
  163.          theDirectory[size] = new DirectoryEntry(name);
  164.     size--; 
  166.     modified = true;
  167.   }
  171.   /** Add an entry to the directory.
  172.       @param name The name of the new person
  173.       @param number The number of the new person
  174.    */
  175.   private void add(String name, String number) {
  176.     if (size >= capacity) {
  177.       reallocate();
  178.     }
  179.     theDirectory[size] = new DirectoryEntry(name, number);
  180.     size++;
  181.   }
  183.   /** Allocate a new array to hold the directory. */
  184.   private void reallocate() {
  185.     capacity *= 2;
  186.     DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
  187.     System.arraycopy(theDirectory, 0, newDirectory, 0,
  188.                      theDirectory.length);
  189.     theDirectory = newDirectory;
  190.   }
  193. }
Sep 10 '09 #1
6 4240
13,262 MVP
Looks like you got some code from somewhere that you don't really understand what it does.
Better start with Sun's Java tutorial.
Sep 11 '09 #2
11,448 Recognized Expert MVP
That remove() method doesn't make sense to me:

Expand|Select|Wrap|Line Numbers
  1.    public void remove(String name) { 
  2.      int i = find(name); 
  3.       if(i <= -1) 
  4.      System.out.println("Entry not found; cannot delete!"); 
  5.      else 
  6.          theDirectory[size] = new DirectoryEntry(name); 
  7.     size--;  
  9.     modified = true; 
  10.   } 
I read it as: try to find that name; if not found print a message otherwise make a new entry? and decrement the size of it all?

kind regards,

Sep 11 '09 #3
55 New Member
Ok if that is what is wrong, then How can I make it delete the entry? I thought decrementing the size of the array would be deleting an entry out of the array. Or do I just decrement the size? Im confused.
Sep 11 '09 #4
11,448 Recognized Expert MVP
For starters: you can't resize an array once you have instantiated one. Better use an ArrayList, you can delete any element from it given the index value of the element.

kind regards,

Sep 11 '09 #5
55 New Member
Well besides making an array list, is there anyway that I can remove an entry. I was thinking of another idea where I could overwrite an element in the array. Like it searches for a name, once the array is found, it takes the name before the found name and replaces moves it up. For instance:

Bob, Ray, Jill

Ray was found, but the remove method allows Bob to replace Ray, thus making it

Bob, Bob, Jill
Sep 11 '09 #6
11,448 Recognized Expert MVP
The ArrayList class object can do that for you with its 'remove()' method; read the API documentation.

kind regards,

Sep 12 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

by: joemono | last post by:
Hello everyone! First, I appologize if this posting isn't proper "netiquette" for this group. I've been working with perl for almost 2 years now. However, my regular expression knowledge is pretty limited. I wrote the following expression to take (hopefully) any _reasonable_ phone number input, and format it as (999) 999-9999 x 9999.
by: William Morris | last post by:
Our application tracks contact information. One of our clients, a car dealership, has asked about being able to enter a lastname and phone number and getting as much of the main form filled out as possible, "Hi, thanks for stopping by Demaux Motors. Before we get started, can I get your phone number, please? Oh, HI Joe, you still live on...
by: Danny Yeadon | last post by:
Hi I need to remove unwanted characters from phone numbers from my phone bill to analyse the data. Some examples are 02 48222222 i need to remove the space +61266667656 i need to remove the + 0427 221 529 i need to remove both spaces 0419 637 344MNET i need to remove the spaces...
by: htperth | last post by:
Hi all, Note that I'm new to LDAP and Active Directory and am writing an application that retrieves a simple phone list for all the users in our domain. So far I have the following console app code that seems to work. It queries Active Directory for a phone list and correctly retrieves the names (cn) from the OU. Though I have asked for...
by: htperth | last post by:
Hi all, Note that I'm new to LDAP and Active Directory and am writing an application that retrieves a simple phone list for all the users in our domain. So far I have the following console app code that seems to work. It queries Active Directory for a phone list and correctly retrieves the names (cn) from the OU. Though I have asked for...
by: homevista | last post by:
PART III: Putting things together In part I we examined the modem to verify that it supported voice. If so, we took a note about the voice data format that we would use. In the second part, we prepared a wave file and implemented a piece of code in C# to be used by HomeZIX to read the wave file into a buffer. Now, it’s time to put things...
by: ryushinyama | last post by:
I am wanting to remove 1's that Canadian customers put in front of their numbers because when FedEx imports them for shipping they leave the 1 and cut off the last number. Other countries numbers don't get formatted the same so they are not an issue. The code below was an attempt to remove a one at the beginning if present at all. Which...
by: Blue Streak | last post by:
Hello, Folks! Does anyone know of a website that lists the local phone number formats for each country? TIA...
by: Propoflady | last post by:
My contacts can have as many as five or six phone numbers - is it possible to make a query that puts the name, and each phone number after it on the same line - for this reason I have two tables - client and phone linked by client id right now I get contact a - phone number 1 contact a - phone number 2 I would like
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.