Hey, I created a phone directory program. But I was wondering if I could get some hints on how I could create a txt file and add, delete names and numbers on the txt file.

import java.util.*;
import java.lang.*;
import java.lang.Object;
import jpb.*;

public class PhoneDir {
    private static LinkedList phone;

    public static void main(String[] args) {


    //Display commands
    System.out.println("List of Commands:\n" +
                              "   a - Show 'a'll records\n" +
                              "   d - 'd'elete the current record\n" +
                              "   f  - change the 'f'irst name in current record\n" +
                              "   l  - change the 'l'ast name in current record\n" +
                              "   n - add a 'n'ew record\n" +
                              "   p - change the 'p'hone number in current record\n" +
                              "   q - 'q'uit\n" +
                              "   s - 's'elect a record from record list\n");

    //Prompt user to enter a command
    SimpleIO.prompt("Enter a command from the list above: ");
    String command = (String) SimpleIO.readLine();

    //Determine if command is legal.
    if (command.equalsIgnoreCase("a"))
    {
      showAll();
    }
       else if (command.equalsIgnoreCase("d"))
       {
         deleteRecord();
       }
       else if (command.equalsIgnoreCase("f"))
       {
         changeFirst();
       }
       else if (command.equalsIgnoreCase("l"))
       {
         changeLast();
       }
       else if (command.equalsIgnoreCase("n"))
       {
         addNew();
       }
       else if (command.equalsIgnoreCase("p"))
       {
         changePhone();
       }
       else if (command.equalsIgnoreCase("q"))
       {
         quit();
       }
       else if (command.equalsIgnoreCase("s"))
       {
         selectRecord();
       }
       else
       {

       //Illegal command will display an error message.
       System.out.println("Illegal command");
       }
    System.out.println();
     }

   //Shows all records in the directory
   private static void showAll(){
try{   
    for (int i = 0; i < phone.size(); i++)
               System.out.println(phone);
 
        }
catch (Exception e) {
    
}    
}

   //Deletes the current record
   private static void deleteRecord()
   {
     SimpleIO.prompt("Enter name to delete: ");
     String key = SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
       String name = curr.getName();
       if (name.startsWith(key));
          
           phone.remove((String) key);
     }
   }

   //Changes the first name of the current record
   private static void changeFirst()
   {
     SimpleIO.prompt("Enter name to change: ");
     String key = SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
       String FirstName = curr.getFirstName();
       if (FirstName.startsWith(key))
         System.out.println(curr.getFirstName() + " " + curr.getFirstName());
     }
     SimpleIO.prompt("Enter name change:");
       phone.add((String) key);
   }

   //Change the last name of the current record
   private static void changeLast()
   {
     SimpleIO.prompt("Enter name to change: ");
     String key = SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
            @SuppressWarnings("LocalVariableHidesMemberVariable")
       String LastName = curr.getLastName().toLowerCase();
       if (LastName.startsWith(key))
         System.out.println(curr.getLastName() + " " + curr.getLastName());
     }
     SimpleIO.prompt("Enter name changes: ");
       phone.add((String) key);  
   }

   //Add a new record
   private static void addNew()
   {
      try {
     int number;
     SimpleIO.prompt("Enter name: ");
     String name = (String) SimpleIO.readLine();
        System.out.print("Enter phone number: " );

    Scanner input = new Scanner(System.in);
    number = input.nextInt();
     phone.add(name);
     phone.add(number);
      }
      catch (Exception e){
          
      }
   }

   //Change the phone number of the current record
   private static void changePhone()
   {
     SimpleIO.prompt("Enter number to change: ");
     String key = (String)SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
       String name = (String) curr.getNumber().toLowerCase();
       if (name.startsWith(key))
         System.out.println(curr.getNumber() + " " + curr.getNumber());
     
     phone.add((String) key);
   }
   }
   //Quits the program
   private static void quit()
    {
      System.exit(0);
    }
   
   //Selects a record from the record list
   private static void selectRecord()
   {
     SimpleIO.prompt("Enter name to change: ");
     String key = SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
       String name = curr.getName().toLowerCase();
       if (name.startsWith(key))
         System.out.println(curr.getName() + " " + curr.getName());
   }
   }
   private String FirstName;
   private String LastName;
   private String name;
   private String number;

   public String getFirstName()
    {
       return FirstName;
    }
   
   public String getLastName()
    {
       return LastName;
    }

   public String getName()
     {
       return name;
     }
   
   public String getNumber()
    {
       return number;
   }


}

Recommended Answers

All 9 Replies

Hey, I created a phone directory program. But I was wondering if I could get some hints on how I could create a txt file and add, delete names and numbers on the txt file.

import java.util.*;
import java.lang.*;
import java.lang.Object;
import jpb.*;

public class PhoneDir {
    private static LinkedList phone;

    public static void main(String[] args) {


    //Display commands
    System.out.println("List of Commands:\n" +
                              "   a - Show 'a'll records\n" +
                              "   d - 'd'elete the current record\n" +
                              "   f  - change the 'f'irst name in current record\n" +
                              "   l  - change the 'l'ast name in current record\n" +
                              "   n - add a 'n'ew record\n" +
                              "   p - change the 'p'hone number in current record\n" +
                              "   q - 'q'uit\n" +
                              "   s - 's'elect a record from record list\n");

    //Prompt user to enter a command
    SimpleIO.prompt("Enter a command from the list above: ");
    String command = (String) SimpleIO.readLine();

    //Determine if command is legal.
    if (command.equalsIgnoreCase("a"))
    {
      showAll();
    }
       else if (command.equalsIgnoreCase("d"))
       {
         deleteRecord();
       }
       else if (command.equalsIgnoreCase("f"))
       {
         changeFirst();
       }
       else if (command.equalsIgnoreCase("l"))
       {
         changeLast();
       }
       else if (command.equalsIgnoreCase("n"))
       {
         addNew();
       }
       else if (command.equalsIgnoreCase("p"))
       {
         changePhone();
       }
       else if (command.equalsIgnoreCase("q"))
       {
         quit();
       }
       else if (command.equalsIgnoreCase("s"))
       {
         selectRecord();
       }
       else
       {

       //Illegal command will display an error message.
       System.out.println("Illegal command");
       }
    System.out.println();
     }

   //Shows all records in the directory
   private static void showAll(){
try{   
    for (int i = 0; i < phone.size(); i++)
               System.out.println(phone);
 
        }
catch (Exception e) {
    
}    
}

   //Deletes the current record
   private static void deleteRecord()
   {
     SimpleIO.prompt("Enter name to delete: ");
     String key = SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
       String name = curr.getName();
       if (name.startsWith(key));
          
           phone.remove((String) key);
     }
   }

   //Changes the first name of the current record
   private static void changeFirst()
   {
     SimpleIO.prompt("Enter name to change: ");
     String key = SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
       String FirstName = curr.getFirstName();
       if (FirstName.startsWith(key))
         System.out.println(curr.getFirstName() + " " + curr.getFirstName());
     }
     SimpleIO.prompt("Enter name change:");
       phone.add((String) key);
   }

   //Change the last name of the current record
   private static void changeLast()
   {
     SimpleIO.prompt("Enter name to change: ");
     String key = SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
            @SuppressWarnings("LocalVariableHidesMemberVariable")
       String LastName = curr.getLastName().toLowerCase();
       if (LastName.startsWith(key))
         System.out.println(curr.getLastName() + " " + curr.getLastName());
     }
     SimpleIO.prompt("Enter name changes: ");
       phone.add((String) key);  
   }

   //Add a new record
   private static void addNew()
   {
      try {
     int number;
     SimpleIO.prompt("Enter name: ");
     String name = (String) SimpleIO.readLine();
        System.out.print("Enter phone number: " );

    Scanner input = new Scanner(System.in);
    number = input.nextInt();
     phone.add(name);
     phone.add(number);
      }
      catch (Exception e){
          
      }
   }

   //Change the phone number of the current record
   private static void changePhone()
   {
     SimpleIO.prompt("Enter number to change: ");
     String key = (String)SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
       String name = (String) curr.getNumber().toLowerCase();
       if (name.startsWith(key))
         System.out.println(curr.getNumber() + " " + curr.getNumber());
     
     phone.add((String) key);
   }
   }
   //Quits the program
   private static void quit()
    {
      System.exit(0);
    }
   
   //Selects a record from the record list
   private static void selectRecord()
   {
     SimpleIO.prompt("Enter name to change: ");
     String key = SimpleIO.readLine();
     for (int i = 0; i < phone.size(); i++)
     {
       PhoneDir curr = (PhoneDir) phone.get(i);
       String name = curr.getName().toLowerCase();
       if (name.startsWith(key))
         System.out.println(curr.getName() + " " + curr.getName());
   }
   }
   private String FirstName;
   private String LastName;
   private String name;
   private String number;

   public String getFirstName()
    {
       return FirstName;
    }
   
   public String getLastName()
    {
       return LastName;
    }

   public String getName()
     {
       return name;
     }
   
   public String getNumber()
    {
       return number;
   }


}

look here for writing to file:http://www.roseindia.net/java/beginners/WriteTextFileExample.shtml and here is something i posted on reading/editing and writing to text files migth help:http://www.daniweb.com/software-development/java/code/408638 This here will also be helpful:http://www.javapractices.com/topic/TopicAction.do?Id=42

http://www.daniweb.com/software-development/java/code/408638

Yes, this one's quite useful. Just go through it and try to understand the logic behind the code. As for printing to files is concerned, just adopt a specific file format and save as per it keeping in mind that you have to read it later. You may want to create a separate Java class specially formatted for storing your kind of data and save the class object as a whole. Try using lists and synchronize them all together.

For example...

public class nameofclass
{
List names;
List numbers;
//etc.
}

You'll have to initialize the list by suffixing

= new ArrayList();

You can find all of this under java.util

Save the class object WITH the lists as a whole to the file. Since you know the contents of the class, you can easily read it back using object-f-input and output.

http://docs.oracle.com/javase/tutorial/essential/io/objectstreams.html is a good tutorial on reading and writing objects to files.

Also, read through the whole trail if you're new to the concept of file input and output, and best of luck. :)

As for printing to files is concerned, just adopt a specific file format and save as per it keeping in mind that you have to read it later.

what do you mean by this?
he already chose to use '.txt'
I assume he'll be reading it through the application he's writing. a simple separator char will do the trick there.

what do you mean by this?
he already chose to use '.txt'
I assume he'll be reading it through the application he's writing. a simple separator char will do the trick there.

You interpreted me wrong. I wasn't talking about the file extension. I was talking about arranging the data in a certain way inside the file.

And yes, a char separator will do, but the code'll be simpler if he tries the object input-output way. It's not complicated at all. (Not that your way's complicated, but I'm just saying)

well, yes, but how are you trying to do so? unless he has a maximum length for his elements ...
sure, he can say:
number name, at which point he just needs to read the line, first String is the number, convert to number, rest of the line is the name, but what if he needs more information?
according to his code, he has (at least) a first and last name. since there are names (both first and last) that contain more than one part (separated by a space), you can't just check String by String. since you can't just say: a name can not be longer than ... unless you accept the risk that certain valid and existing names will not be able to be used in your application, you also can't use a max length, unless you make this length way too long for most of the names, so I think going with a separator char is about the best way.

well, yes, but how are you trying to do so? unless he has a maximum length for his elements ...
sure, he can say:
number name, at which point he just needs to read the line, first String is the number, convert to number, rest of the line is the name, but what if he needs more information?
according to his code, he has (at least) a first and last name. since there are names (both first and last) that contain more than one part (separated by a space), you can't just check String by String. since you can't just say: a name can not be longer than ... unless you accept the risk that certain valid and existing names will not be able to be used in your application, you also can't use a max length, unless you make this length way too long for most of the names, so I think going with a separator char is about the best way.

No, you're not getting me. I'll just post some code, wait.

You can do something like this:-

public class sera
{
List ofNames = new ArrayList(); //assume that I've imported all necessary pkgs
List ofNumbers = new ArrayList();
}
//..............
void whatever()
{
sera xyz = new sera();
//take in the values and fill in xyz
//serialize xyz
}
//this is it, now?

What I wanna show is that the whole object is being serialized as a whole. I've pasted a link to The Java Tutorials on this. This way, when you read it, you get the lists of all the people in one go in a variable during execution and you can manip. it.

you make a valid point, but if you look at the original code, is that a class you would serialize? :)

Now you make a valid point. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.