banner



How To Create A Address Book Using Java

#1

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 31
  • Joined: 17-September 14

Address Book Program

Posted 19 October 2014 - 10:45 AM

So for the last few weeks I have been working on a Java project for school. I see the light at the end of the tunnel, but I have run into some speed bumps with my main class. It was working fine, but I was pulling an all nighter and I deleted some of my code by mistake.

Now I am not seeing what is exactly wrong. I want to point out that I am a complete novice to Java so I might night see things right away that someone with more experience could see in an instant.

Anyways, the project was to create an address book complete with a menu system.

Here are all of my classes:

AddressBook

import java.util.ArrayList;  /**  * A model of an address book which keeps track of contacts. An address book  * object should keep track of the concept of a current contact (think index).  * You must use an ArrayList for your implementation.  */ public class AddressBook { 	Contact contact = new Contact();  	/** 	 * Default constructor for an address book. You should initialize your 	 * objects here. 	 */ 	public AddressBook() { 		currentContactIndex = null; 	}  	/** 	 * Add a contact by passing in a constructed contact object filled with 	 * data. The current contact should be updated to refer to the index of the 	 * newly added contact. 	 *  	 * @param contact 	 *            the contact object to add to the address book. 	 */ 	public void addContact(Contact contact) { 		contacts.add(contact); 		currentContactIndex = contacts.size() - 1;  	}  	// Temporary printout  	public void printItems() { 		for (Contact contact : contacts) 			System.out.println("*** = " + contact); 	}  	/** 	 * Remove a contact by deleting what ever index the current contact refers 	 * to. The current contact index should be updated to point at the next 	 * contact in the list. 	 */ 	public void deleteContact() { 		if (contacts.size() == 0) 			return; 		contacts.remove(currentContactIndex.intValue()); 		if (currentContactIndex == contacts.size()) { 			currentContactIndex = currentContactIndex - 1; 		} 		if(contacts.size()==0) 			currentContactIndex = null; 	}  	/** 	 * Update the current contact index to refer to the next contact in the 	 * list. If you are at the last item in the list then you should update the 	 * current contact index to point at the first contact in the list. 	 */ 	public void next() { 		if (contacts.size() == 0) 			return; 		currentContactIndex = currentContactIndex + 1; 		if (currentContactIndex == contacts.size()) 			currentContactIndex = 0; 	}  	/** 	 * Update the current contact index to refer to the next contact in the 	 * list. If you are at the first item in the list then you should update the 	 * current contact index to point at the last contact in the list. 	 */ 	public void previous() { 		if (contacts.size() == 0) 			return; 		else 			currentContactIndex = currentContactIndex - 1; 		if (currentContactIndex == -1) 			currentContactIndex = contacts.size() - 1;  	}  	/** 	 * Check if the address book has any contacts in it or not. 	 *  	 * @return true if there are no contacts in the address book, otherwise 	 *         false 	 */ 	public Boolean isEmpty() { 		boolean isEmpty = contacts.isEmpty(); 		return isEmpty; 	}  	/** 	 * Update a single field of the current contact. This can also be used to 	 * update a contact with a new custom field. 	 *  	 * @param fieldName 	 *            the name of the field to update 	 * @param fieldValue 	 *            the value of the field to update to 	 * @throws Exception 	 */ 	public void updateContact(String fieldName, String fieldValue) { 		if (contacts.size() == 0) 			return; 		switch (fieldName.toLowerCase()) { 		case "firstname": 		case "first name": 			getCurrentContact().setFirstName(fieldValue); 			break; 		case "lastname": 		case "last name": 			getCurrentContact().setLastName(fieldValue); 			break; 		case "phonenumber": 		case "phone number": 			getCurrentContact().setPhoneNumber(fieldValue); 			break; 		case "emailaddress": 		case "email address": 			getCurrentContact().setEmailAddress(fieldValue); 			break; 		default: 			getCurrentContact().setCustomField(fieldName, fieldValue); 		} 	}  	/** 	 * Get the current number of contacts in the address book. 	 *  	 * @return the count as an integer of the number of contacts in the address 	 *         book 	 */ 	public Integer getContactCount() { 		if (contacts == null) { 			contactCount = 0; 		} else 			contactCount = contacts.size(); 		return contactCount; 	}  	/** 	 * Get the contact object that the current contact index refers to 	 *  	 * @return the current contact object 	 */ 	public Contact getCurrentContact() { 		if (currentContactIndex != null) 			return contacts.get(currentContactIndex); 		else 			return null; 	}  	/** 	 * Search for a string value within a contact. If the provided value exists 	 * anywhere within a contact, it should be considered a match. If multiple 	 * contacts are found to have a match then both should be returned. 	 *  	 * @param valueToSearchFor 	 *            the string value to search for in a contact 	 * @return a list of contacts that contain the string value provided 	 */ 	public ArrayList<Contact> searchForContact(String valueToSearchFor) { 		searchHits.clear(); 		for (Contact value : contacts) 			if (value.toString().toLowerCase().contains(valueToSearchFor.toLowerCase())) 				searchHits.add(value); 		return searchHits; 	}  	public ArrayList<Contact> getContacts() { 		return contacts; 	}  	public void setContacts(ArrayList<Contact> contacts) { 		this.contacts = contacts; 	}  	public Integer getCurrentContactIndex() { 		return currentContactIndex; 	}  	public void setCurrentContactIndex(Integer currentContactIndex) { 		this.currentContactIndex = currentContactIndex; 	}  	private int contactCount; 	private ArrayList<Contact> searchHits = new ArrayList<Contact>(); 	private ArrayList<Contact> contacts = new ArrayList<Contact>(); 	private Integer currentContactIndex; }            

Contact

import java.util.HashMap;  /**  * Models a Contact with a first name, last name, phone number, email address,  * and any variable number of custom fields.  */ public class Contact {  	String firstName, lastName, phoneNumber, emailAddress, toString;  	/** 	 * Default constructor used for testing. This must be inserted here since we 	 * have a custom constructor and java no longer creates a default 	 * constructor when you have a custom constructor. You must initialize your 	 * objects here. 	 */  	public Contact() { 		firstName = lastName = phoneNumber = emailAddress = toString = null; 		this.customField = new HashMap<String,String>(); 	}  	/** 	 * Custom constructor that builds a contact with the specified values. Does 	 * not include custom fields. You must initialize your objects here. 	 *  	 * @param firstName 	 *            the first name of the contact 	 * @param lastName 	 *            the last name of the contact 	 * @param phoneNumber 	 *            the phone number of the contact 	 * @param emailAddress 	 *            the email address of the contact 	 */ 	public Contact(String firstName, String lastName, String phoneNumber, 			String emailAddress) { 		this.firstName = firstName; 		this.lastName = lastName; 		this.phoneNumber = phoneNumber; 		this.emailAddress = emailAddress; 		this.customField = new HashMap<String,String>(); 	}  	/** 	 * Getter for the first name of this contact. Allows the AddressBook 	 * developer to get the value of the first name of a contact. 	 *  	 * @return the first name of the contact as a string 	 */ 	public String getFirstName() { 		return firstName; 	}  	/** 	 * Setter for the first name of this contact. Allows the AddressBook 	 * developer to set the value of the first name of a contact. 	 *  	 * @param firstName 	 *            the first name as a string to set to 	 */ 	public void setFirstName(String firstName) { 		this.firstName = firstName;  	}  	/** 	 * Getter for the last name of this contact. Allows the AddressBook 	 * developer to get the value of the last name of a contact. 	 *  	 * @return the last name of the contact as a string 	 */ 	public String getLastName() { 		return lastName; 	}  	/** 	 * Setter for the last name of this contact. Allows the AddressBook 	 * developer to set the value of the last name of a contact. 	 *  	 * @param lastName 	 *            the last name as a string to set to 	 */ 	public void setLastName(String lastName) { 		this.lastName = lastName; 	}  	/** 	 * Getter for the phone number of this contact. Allows the AddressBook 	 * developer to get the value of the phone number of a contact. 	 *  	 * @return the phone number of the contact as a string 	 */ 	public String getPhoneNumber() { 		return phoneNumber; 	}  	/** 	 * Setter for the phone number of this contact. Allows the AddressBook 	 * developer to set the value of the phone number of a contact. 	 *  	 * @param phoneNumber 	 *            the phone number as a string to set to 	 */ 	public void setPhoneNumber(String phoneNumber) { 		this.phoneNumber = phoneNumber; 	}  	/** 	 * Getter for the email of this contact. Allows the AddressBook developer to 	 * get the value of the email of a contact. 	 *  	 * @return the email of the contact as a string 	 */ 	public String getEmailAddress() { 		return emailAddress; 	}  	/** 	 * Setter for the email of this contact. Allows the AddressBook developer to 	 * set the value of the email of a contact. 	 *  	 * @param emailAddress 	 *            the email as a string to set to 	 */ 	public void setEmailAddress(String emailAddress) { 		this.emailAddress = emailAddress; 	}  	/** 	 * Get a representation of the custom fields of this contact. 	 *  	 * @return a Map representation of custom fields with name of the field as 	 *         the "key" and the value of the field as the "value" 	 */ 	public HashMap<String, String> getCustomFields() { //			if(customField == null) //				customField = new HashMap<String,String>();			 			return customField; 	}  	/** 	 * Adds a custom field to a contact with a specified value. Can be used to 	 * update an existing field to a new value. 	 *  	 * @param fieldName 	 *            the name of the field to create or update 	 * @param fieldValue 	 *            the value of to set this custom field to, will overwrite a 	 *            preexisting value if field already exists 	 */ 	public void setCustomField(String fieldName, String fieldValue) { //		if(customField == null) //			customField = new HashMap<String,String>(); 		customField.put(fieldName, fieldValue); 	}  	/** 	 * Provides a string representation of a contact. Use your string parsing 	 * knowledge to make the string look like what's required by the contact 	 * tests. 	 *  	 * @return a string representation of a contact 	 */ 	public String toString() {  		toString = "First Name: " + firstName + "\nLast Name: " + lastName 				+ "\nPhone Number: " + phoneNumber + "\nEmail Address: " 				+ emailAddress; 		if (customField.size() == 0) 			return toString; 		else { 			for (String key : customField.keySet()) 				toString = toString + "\n" + key + ": " + customField.get(key); 			return toString; 		}  	}  	//Declares a new HashMap so that "customField" can be stored 	private HashMap<String, String> customField;  }            

MenuSystem

public class MenuSystem { 	 	//Contains static displays for both the main menu and sub menus  	public void displayMainMenu() { 		System.out.println(); 		System.out.println("-------- WELCOME TO YOUR ADDRESS BOOK --------"); 		System.out.println("-         1. display next contact            -"); 		System.out.println("-         2. display previous contact        -"); 		System.out.println("-         3. add a contact                   -"); 		System.out.println("-         4. delete a contact                -"); 		System.out.println("-         5. update a contact                -"); 		System.out.println("-         6. display number of contacts      -"); 		System.out.println("-         7. search for a contact            -"); 		System.out.println("-         8. quit application                -"); 		System.out.println("----------------------------------------------"); 		System.out.println(); 	}  	public void displayAddContactMenu() { 		System.out.println(); 		System.out.println("***** ADD CONTACT MENU *****"); 		System.out 				.println("Please enter contact information."); 	}  	public void displayDeleteContactMenu() { 		System.out.println(); 		System.out.println("***** DELETE CONTACT MENU *****"); 		System.out 				.println("Are you sure you wanted to delete the currently displayed contact? (Y/[N]"); 	}  	public void displayUpdateContactMenu() { 		System.out.println(); 		System.out.println("***** UPDATE CONTACT MENU *****"); 		System.out 				.print("Enter a field name and field value separated by a comma:"); 	}  	public void displayNumberOfContactsMenu() { 		System.out.println(); 		System.out.println("***** DISPLAY NUMBER OF CONTACTS MENU *****"); 		System.out.print("Number of contacts: "); 	}  	public void displaySearchForContactMenu() { 		System.out.println(); 		System.out.println("***** SEARCH FOR CONTACT MENU *****"); 		System.out.print("Enter a value to search for: "); 	}  	public void displayQuitApplicationMenu() { 		System.out.println(); 		System.out.println("***** QUIT APPLICATION MENU *****"); 		System.out 				.print("Are you sure you want to quit the application? (Y/[N]) : "); 	}  }            

Main

import static org.junit.Assert.assertEquals;  import java.util.HashMap; import java.util.Scanner; import java.util.ArrayList;  public class Main {  	public static void main(String[] args) {  		// Initiation of variables 		MenuSystem menuSystem = new MenuSystem(); 		AddressBook addressBook = new AddressBook(); 		Scanner in = new Scanner(System.in); 		Contact contact = new Contact(); 		Boolean quit = false; 		boolean customFieldBoolean = false; 		String repeat; 		String yesOrNo = "n"; 		boolean validInput; 		; 		String crudeMenuChoice = null;  		// The main loop that will loop until the application closes 		do {  			// Displays the main menu system 			repeat = null; 			menuSystem.displayMainMenu();  			// Displays contact if there is a current one, else alerts. 			if (addressBook.getCurrentContact() != null) { 				System.out.println("*****Current Contact*****"); 				System.out.println(addressBook.getCurrentContact().toString()); 			} else { 				System.out.println("*****No Current Contact*****"); 			}  			// Asks for user to input menu # and then stores it in menuChoice variable 			System.out.println(); 			System.out 					.print("Please choose a menu item above by entering a number (1-8): ");  			validInput = false; 			// Catches invalid inputs repeats until it receives the acceptable input 			while (validInput == false) { 				validInput = true; 				crudeMenuChoice = in.nextLine();  				try { 					int menuChoice = Integer.parseInt(crudeMenuChoice);  				} catch (Exception e) { 					validInput = false; 					System.out.println(); 					System.out.print("Invalid input, try again: ");  				} finally { 					if (validInput == true) { 						int menuChoice = Integer.parseInt(crudeMenuChoice); 						if (1 > menuChoice || 8 < menuChoice) { 							validInput = false; 							System.out.println(); 							System.out.print("Invalid number, try again: "); 						} 					}  				}  			} 			// Converts the input into a legitimate integer 			int menuChoice = Integer.parseInt(crudeMenuChoice);  			// Main switch which takes user the menu number that they have selected 			switch (menuChoice) { 			case 1: // displays next contact 				addressBook.next();  				break; 			case 2: // displays previous contact 				addressBook.previous();  				break; 			case 3: // Adds a new contact 				// Gathers default field values first 				menuSystem.displayAddContactMenu(); 				contact = new Contact(); 				System.out.println(); 				System.out.print("Enter First Name: "); 				String firstName = in.nextLine(); 				contact.setFirstName(firstName); 				System.out.print("Enter Last Name: "); 				String lastName = in.nextLine(); 				contact.setLastName(lastName); 				System.out.print("Enter Phone Number: "); 				String phoneNumber = in.nextLine(); 				contact.setPhoneNumber(phoneNumber); 				System.out.print("Enter Email: "); 				String email = in.nextLine(); 				contact.setEmailAddress(email); 				addressBook.addContact(contact);  				// Gives user the option to add a custom field while creating a "new" contact  				System.out.print("(Optional) Custom Field (Y/N)? "); 				yesOrNo = in.nextLine(); 				if (yesOrNo.toLowerCase().equals("y")) { 					customFieldBoolean = false; 					while (customFieldBoolean == false) { 						System.out.print("Enter your custom fields name: "); 						String customField = in.nextLine(); 						System.out.print("Enter a value for" + customField 								+ ":"); 						String customFieldValue = in.nextLine(); 						contact.setCustomField(customField, customFieldValue); 						System.out 								.print("Would you like to add another custom field (Y/N): "); 						yesOrNo = in.nextLine();  						// functionality to add another custom field should the 						// user feel so inclined. 						if (yesOrNo.toLowerCase().equals("n")) 							customFieldBoolean = true; 					} 				} 				break;  			case 4: // Deletes a contact 				menuSystem.displayDeleteContactMenu(); 				yesOrNo = in.nextLine(); 				if (yesOrNo.toLowerCase().equals("y")) 					addressBook.deleteContact(); 				break;  			case 5: // Updates a contact 				menuSystem.displayUpdateContactMenu(); 				String crudeUpdateInfo = in.nextLine(); 				if (crudeUpdateInfo.contains(",")) 					addressBook.updateContact(crudeUpdateInfo.substring(0, 							crudeUpdateInfo.indexOf(",")), crudeUpdateInfo 							.substring(crudeUpdateInfo.indexOf(",") + 1, 									crudeUpdateInfo.length())); 				else 					System.out 							.println("Info was not entered correctly, please make sure to use a comma!"); 					System.out.println("Press [Enter] to continue"); 					repeat = in.nextLine(); 					if (!repeat.equals(null)) 					break; 				break;  			case 6: // Displays number of current contacts 				menuSystem.displayNumberOfContactsMenu(); 				System.out.println(addressBook.getContactCount()); 				System.out.println(); 				System.out.println("Press [Enter] to continue"); 				repeat = in.nextLine(); 				if (!repeat.equals(null)) 					break;  			case 7: // Searches for a contact and gives option to display the search results 				menuSystem.displaySearchForContactMenu(); 				String searchInfo = in.nextLine(); 				ArrayList<Contact> matches = addressBook 						.searchForContact(searchInfo); 				if (matches.size() == 0) { 					System.out.println("There were 0 results found."); 					System.out.println(); 					System.out.println("Press [Enter] to continue"); 					repeat = in.nextLine(); 					if (!repeat.equals(null)) 						break; 				} else 					System.out.println("There were " + matches.size() 							+ " results found."); 				System.out 						.println("Would you like to print out the results (Y/N)?"); 				yesOrNo = "n"; 				yesOrNo = in.nextLine(); 				if (yesOrNo.toLowerCase().equals("y")) {  					System.out.println("**********"); 					System.out.println("Search Results:"); 					System.out.println(); 					for (Contact match : matches) { 						System.out.println(match.toString()); 						System.out.println("----------"); 					} 					System.out.println("**********");  					System.out.println(); 					System.out.println("Press [Enter] to continue"); 					repeat = in.nextLine(); 					if (!repeat.equals(null)) 						break; 				} else 					break; 			case 8: // Terminates the application 				menuSystem.displayQuitApplicationMenu(); 				yesOrNo = in.nextLine(); 				if (yesOrNo.toLowerCase().equals("y")) { 					System.out.println(); 					System.out.println("***** Application terminated. *****"); 					quit = true; 				} 				break; 			default: // Default output for invalid inputs that pass the filters above the switch 				System.out.println(); 				System.out.println("Unknown error!"); 				break; 			}  		} while (quit != true);  	} }            

The problem I am having is with the main class. It keeps telling me that the import cannot be resovled. I accidently deleted this part of the code and the next morning I realized it was missing. I put it back and it hasn't been working since. I just need some fresh eyes to look at this because I am slightly confused (and tired).

I also have tests from my professor if you want to see them.

This post has been edited by macosxnerd101: 19 October 2014 - 12:14 PM
Reason for edit:: Please use a descriptive title


Is This A Good Question/Topic? 0

  • +

#2 g00se User is offline

Reputation: 3744

  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: Address Book Program

Posted 19 October 2014 - 11:56 AM

Start by commenting out the JUnit import in main

#3 DroidsEatApples User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 31
  • Joined: 17-September 14

Re: Address Book Program

Posted 19 October 2014 - 02:59 PM

Well I commented it out and though it helped I have 3 new warnings.

The first warning is at line 5 which says import java.util.HashMap; is never used.

The second error is a resource leak (which I have never heard of) at line 16 which is scanner in = new Scanner(System.in);... it says "in" is also never used.

My last warning is at line 53 and it says the local variable menuChoice is not used.

#4 g00se User is offline

Reputation: 3744

  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: Address Book Program

Posted 19 October 2014 - 04:05 PM

OK. So either ignore those warnings or remove the unused stuff

How To Create A Address Book Using Java

Source: https://www.dreamincode.net/forums/topic/356104-address-book-program/

Posted by: weaverhousee82.blogspot.com

0 Response to "How To Create A Address Book Using Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel