Simple Address Book in Java with Source Code

Simple Address Book in Java with Source Code

Simple Address Book in Java

Creating an address book application is a fantastic project for beginner Java developers. It introduces core programming concepts like data structures, user input handling, and file I/O. In this blog post, we’ll walk through building a simple address book application that allows users to add, view, and delete contacts.

Project Overview

Our address book will consist of the following features:

  • Add a new contact:A name, phone number, and email can be entered by users.
  • View contacts: Users can see all the contacts stored in the address book.
  • Delete a contact: Users can remove a contact by specifying the name.
  • Save and load contacts: The application will save contacts to a file and load them when started.

Download New Real Time Projects :-Click here

Setting Up the Project

  1. Create a new Java project: Any IDE, such as Eclipse or IntelliJ IDEA, or even a basic text editor, will do.
  2. Create a new Java class named AddressBook.

https://updategadh.com/category/php-project

AddressBook Class Implementation

Here’s a simple implementation of the AddressBook class:

import java.io.*;
import java.util.*;

class Contact {
    String name;
    String phone;
    String email;

    Contact(String name, String phone, String email) {
        this.name = name;
        this.phone = phone;
        this.email = email;
    }

    @Override
    public String toString() {
        return "Name: " + name + ", Phone: " + phone + ", Email: " + email;
    }
}

public class AddressBook {
    private List<Contact> contacts;
    private static final String FILE_NAME = "contacts.txt";

    public AddressBook() {
        contacts = new ArrayList<>();
        loadContacts();
    }

    public void addContact(String name, String phone, String email) {
        contacts.add(new Contact(name, phone, email));
        saveContacts();
    }

    public void viewContacts() {
        if (contacts.isEmpty()) {
            System.out.println("No contacts found.");
            return;
        }
        for (Contact contact : contacts) {
            System.out.println(contact);
        }
    }

    public void deleteContact(String name) {
        Iterator<Contact> iterator = contacts.iterator();
        boolean found = false;
        while (iterator.hasNext()) {
            Contact contact = iterator.next();
            if (contact.name.equalsIgnoreCase(name)) {
                iterator.remove();
                found = true;
                break;
            }
        }
        if (found) {
            saveContacts();
            System.out.println("Contact deleted: " + name);
        } else {
            System.out.println("Contact not found: " + name);
        }
    }

    private void saveContacts() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME))) {
            for (Contact contact : contacts) {
                writer.write(contact.name + "," + contact.phone + "," + contact.email);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("Error saving contacts: " + e.getMessage());
        }
    }

    private void loadContacts() {
        try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 3) {
                    contacts.add(new Contact(parts[0], parts[1], parts[2]));
                }
            }
        } catch (IOException e) {
            System.out.println("Error loading contacts: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        AddressBook addressBook = new AddressBook();
        Scanner scanner = new Scanner(System.in);
        String choice;

        do {
            System.out.println("\nAddress Book Menu:");
            System.out.println("1. Add Contact");
            System.out.println("2. View Contacts");
            System.out.println("3. Delete Contact");
            System.out.println("4. Exit");
            System.out.print("Enter your choice: ");
            choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    System.out.print("Enter name: ");
                    String name = scanner.nextLine();
                    System.out.print("Enter phone: ");
                    String phone = scanner.nextLine();
                    System.out.print("Enter email: ");
                    String email = scanner.nextLine();
                    addressBook.addContact(name, phone, email);
                    break;
                case "2":
                    addressBook.viewContacts();
                    break;
                case "3":
                    System.out.print("Enter name to delete: ");
                    String deleteName = scanner.nextLine();
                    addressBook.deleteContact(deleteName);
                    break;
                case "4":
                    System.out.println("Exiting...");
                    break;
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        } while (!choice.equals("4"));

        scanner.close();
    }
}

Explanation of the Code

  • Contact Class: This class holds the details of a contact—name, phone number, and email.
  • AddressBook Class:
  • List of Contacts: It maintains a list of Contact objects.
  • Methods:
    • addContact(): Adds a new contact and saves the updated list.
    • viewContacts(): Displays all contacts.
    • deleteContact(): Removes a contact and updates the file.
    • saveContacts(): Saves contacts to a text file.
    • loadContacts(): Loads contacts from the text file at startup.
  • Main Method: Gives users the ability to interact with the address book using a straightforward command-line interface.
See also  How to Make a Clock Using HTML, CSS, and JavaScript

Running the Program

To run the program, compile the Java file and execute the main method. Follow the prompts to add, view, or delete contacts.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *