Results 1 to 7 of 7

Thread: Treemap's

  1. #1
    Russo is offline Member
    Join Date
    Aug 2009
    Posts
    17
    Rep Power
    0

    Default Treemap's

    Hi,

    Im having trouble understanding how to use treemap's.

    With a treemap are how can you enter in multiple information?

    eg.

    key - Name
    data - Address
    data - Suburb
    data - Phone Number

    Thanks in advance

  2. #2
    Russo is offline Member
    Join Date
    Aug 2009
    Posts
    17
    Rep Power
    0

    Default

    Also here is my code so far.

    Java Code:
    import java.io.*;
    
    import java.util.Map;
    import java.util.TreeMap;
    import java.util.Scanner;
    
    
    
    
    public class working {
       
       /**
        * The name of the file in which the address book data is kept.  The
        * file is stored in the user's home directory.  The "." at the
        * beginning of the file name means that the file will be a
        * "hidden" file on Unix-based computers, including Linux and
        * Mac OS X.
        */
       private static String DATA_FILE_NAME = ".txt";
       
       
       public static void main(String[] args) {
          
          String name, number, address;  // Name and number of an entry in the directory
                                        // (used at various places in the program).
    
          TreeMap<String,String>  AddressBook;   // Address Book data structure.
                                               // Enties are name/number pairs.
          
          AddressBook = new TreeMap<String,String>();
          
          
          /* Create a dataFile variable of type File to represent the
           * data file that is stored in the user's home directory.
           */
          
          File userHomeDirectory = new File( System.getProperty("user.home") );
          File dataFile = new File( userHomeDirectory, DATA_FILE_NAME );
          
          
          /* If the data file already exists, then the data in the file is
           * read and is used to initialize the phone directory.  The format
           * of the file must be as follows:  Each line of the file represents
           * one directory entry, with the name and the number for that entry
           * separated by the character '%'.  If a file exists but does not
           * have this format, then the program terminates; this is done to
           * avoid overwriting a file that is being used for another purpose.
           */
          
          if ( ! dataFile.exists() ) {
             System.out.println("No Address book data file found.");
             System.out.println("A new one will be created.");
             System.out.println("File name:  " + dataFile.getAbsolutePath());
          }
          else {
             System.out.println("Reading Address book data...");
             try {
                Scanner scanner = new Scanner( dataFile );
                while (scanner.hasNextLine()) {
                   String phoneEntry = scanner.nextLine();
                   int separatorPosition = phoneEntry.indexOf('%');
                   if (separatorPosition == -1)
                      throw new IOException("File is not an Address book data file.");
                   name = phoneEntry.substring(0, separatorPosition);
                   number = phoneEntry.substring(separatorPosition+1);
                   address = phoneEntry.substring(separatorPosition+2);
                   AddressBook.put(name,number);
                   AddressBook.put(name,address);
                }
             }
             catch (IOException e) {
                System.out.println("Error in Address book data file.");
                System.out.println("File name:  " + dataFile.getAbsolutePath());
                System.out.println("This program cannot continue.");
                System.exit(1);
             }
          }
          
          
          /* Read commands from the user and carry them out, until the
           * user gives the "Exit from program" command.
           */
          
          Scanner in = new Scanner( System.in );
          boolean changed = false;  // Have any changes been made to the directory?
          
          mainLoop: while (true) {
             System.out.println("\nSelect the action that you want to perform:");
             System.out.println("   1.  Look up a Address.");
             System.out.println("   2.  Add or change a phone number.");
             System.out.println("   3.  Remove an entry from your Address Book.");
             System.out.println("   4.  List the entire Address Book.");
             System.out.println("   5.  Exit from the program.");
             System.out.println("Enter action number (1-5):  ");
             int command;
             if ( in.hasNextInt() ) {
                command = in.nextInt();
                in.nextLine();
             }
             else {
                System.out.println("\nILLEGAL RESPONSE.  YOU MUST ENTER A NUMBER.");
                in.nextLine();
                continue;
             }
             switch(command) {
             case 1:
                System.out.print("\nEnter the name who you want to look up: ");
                name = in.nextLine().trim().toLowerCase();
                number = AddressBook.get(name);
                address = AddressBook.get(name);
                if (number == null)
                   System.out.println("\nSORRY, NO DETAILS FOUND FOR " + name);
                else
                   System.out.println("\nADDRESS FOR " + name + ":  " + number);
                break;
             case 2:
                System.out.print("\nEnter the name: ");
                name = in.nextLine().trim().toLowerCase();
                if (name.length() == 0)
                   System.out.println("\nNAME CANNOT BE BLANK.");
                else if (name.indexOf('%') >= 0)
                   System.out.println("\nNAME CANNOT CONTAIN THE CHARACTER \"%\".");
                else {
                    System.out.print("Enter Contact Address: ");
                   number = in.nextLine().trim();
                   System.out.print("Enter phone number: ");
                   address = in.nextLine().trim();
                   if (number.length() == 0)
                      System.out.println("\nADDRESS CANNOT BE BLANK.");
                   else {
                      AddressBook.put(name,number);
                      AddressBook.put(name,address);
                      changed = true;
                   }
                }
                break;
             case 3:
                System.out.print("\nEnter the name whose entry you want to remove: ");
                name = in.nextLine().trim().toLowerCase();
                number = AddressBook.get(name);
                if (number == null)
                   System.out.println("\nSORRY, THERE IS NO ENTRY FOR " + name);
                else {
                   AddressBook.remove(name);
                   changed = true;
                   System.out.println("\nDIRECTORY ENTRY REMOVED FOR " + name);
                }
                break;
             case 4:
                System.out.println("\nLIST OF ENTRIES IN YOUR PHONE BOOK:\n");
                for ( Map.Entry<String,String> entry : AddressBook.entrySet() )
                   System.out.println("   " + entry.getKey() + ": " + entry.getValue() );
                break;
             case 5:
                System.out.println("\nExiting program.");
                break mainLoop;
             default:
                System.out.println("\nILLEGAL ACTION NUMBER.");
             }
          }
          
          
          /* Before ending the program, write the current contents of the
           * phone directory, but only if some changes have been made to
           * the directory.
           */
          
          if (changed) {
             System.out.println("Saving phone directory changes to file " + 
                   dataFile.getAbsolutePath() + " ...");
             PrintWriter out;
             try {
                out = new PrintWriter( new FileWriter(dataFile) );
             }
             catch (IOException e) {
                System.out.println("ERROR: Can't open data file for output.");
                return;
             }
             for ( Map.Entry<String,String> entry : AddressBook.entrySet() )
                out.println(entry.getKey() + "%" + entry.getValue() );
             out.close();
             if (out.checkError())
                System.out.println("ERROR: Some error occurred while writing data file.");
             else
                System.out.println("Done.");
          }
       
       }
    
    }

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I think that what you are trying to do -- use a TreeMap<String, String> is your primary problem. Instead how about create a class that holds all of the personal data together -- the name, address, phone, say we'll call this class PersonalData, and then create a TreeMap<String, PersonalData>. The key will likely be the same, perhaps name? unique key number?

  4. #4
    Russo is offline Member
    Join Date
    Aug 2009
    Posts
    17
    Rep Power
    0

    Default

    If I wanted to use external classes.. eg

    Address.java
    Name.java

    how would I import them? I could use them in the treemap.

    would it be like Address info = new Address(); ?

    Where public class is

    Java Code:
    public class Address
    {
    	/** the street part of the address */
    	private String streetAddress;
    	/** the city part of the address */
    	private String city;
    
    	/**
    	 * Default constructor, fields set to blank strings.
    	 */
    	public Address()
    	{
    		setAddress("", "");
    	}
    
    	/**
    	 * Constructor sets fields to values of parameters
    	 *
    	 * @param sAddress		a String of the address
    	 * @param city			a String of the city
    	 */
    	public Address(String sAddress, String city)
    	{
    		setAddress(sAddress, city);
    	}
    
    	/**
    	 * Prints out the address on 2 lines
    	 */
    	public void print()
    	{
    		System.out.println(streetAddress);
    		System.out.println(city);
    	}
    
    	/**
    	 * Sets the  String value of this instance
    	 *
    	 * @return		a String of this address
    	 */
    	public String toString()
    	{
    		return (streetAddress + "\n" + city);
    	}
    
    	/**
    	 * a mutator method to set the address and city fields
    	 *
    	 * @param sAddress		a String of the address
    	 * @param city			a String of the city
    	 */
    	public void setAddress(String sAddress, String city)
    	{
    		streetAddress = sAddress;
    		this.city = city;
    	}
    
    	/**
    	 * Accessor method for the street address field
    	 *
    	 * @return			the streetAddress String
    	 */
    	public String getStreetAddress()
    	{
    		return streetAddress;
    	}
    
    	/**
    	 * Accessor method for the city field
    	 *
    	 * @return			the city String
    	 */
    	public String getCity()
    	{
    		return city;
    	}
    
    	/**
    	 * This method takes an Address instance as a parameter and
    	 * copies its address fields into this Address instance.
    	 *
    	 * @param otherAddress	an Address object
    	 */
    	public void copyAddress(Address otherAddress)
    	{
    		streetAddress = otherAddress.getStreetAddress();
    		city = otherAddress.getCity();
    	}
    }
    Last edited by Russo; 10-10-2009 at 08:01 AM.

  5. #5
    Russo is offline Member
    Join Date
    Aug 2009
    Posts
    17
    Rep Power
    0

    Default

    I think I was asking the wrong question how do I Call a method from another class?

    from what I thought Address info = new Address(); would be correct, however it returns an error saying class, enum or interface expected... im not sure what that means...

  6. #6
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Suppose you have a class A with a method aMethod

    Java Code:
    class A {
     public void aMethod() {}
    }
    ;

    To call that method in the main class of another class B you do

    Java Code:
    class B {
      public static void main(String[] args) {
       A anA = new A(); //create an object of type A and get the reference to it.
       anA.aMethod(); //call the method using the reference you acquired.
      }
    }

  7. #7
    Russo is offline Member
    Join Date
    Aug 2009
    Posts
    17
    Rep Power
    0

    Default

    Thanks for clearing that up. I worked out the silly mistake i was doing :) I put that code outside of the class.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •