Building a Simple Expense Tracker in Java

In this blog post, we will build a very simple Expense Tracker in Java. Note that we will use Core Java to write the code and text file to store the expense data.

Requirements

Familiarity with Java's core concepts, especially classes, objects, and file operations. An environment to run Java programs, e.g., Eclipse, IntelliJ IDEA, or the JDK's command-line tools. 

Steps to Create the Expense Tracker

Design the Expense Class: This class will represent an individual expense. 

Data Persistence: We'll use simple file I/O to save and load expenses. 

Main Tracker Class: This will offer a menu-driven interface for users to add, view, or delete expenses.

Implementation

The Expense Class:

Represents individual expenses.
public class Expense {
    private String date;
    private String description;
    private double amount;

    public Expense(String date, String description, double amount) {
        this.date = date;
        this.description = description;
        this.amount = amount;
    }

    public String getDate() {
        return date;
    }

    public String getDescription() {
        return description;
    }

    public double getAmount() {
        return amount;
    }

    @Override
    public String toString() {
        return "Expense(date=" + date + ", description=" + description + ", amount=" + amount + ")";
    }
}

2. ExpenseStorage Class: 

Handles data persistence. It saves and loads expense data from a text file.

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

public class ExpenseStorage {
    private static final String FILENAME = "expenses.txt";

    public static void saveExpenses(ArrayList<Expense> expenses) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(FILENAME))) {
            for (Expense e : expenses) {
                writer.println(e.getDate() + "," + e.getDescription() + "," + e.getAmount());
            }
        } catch (IOException e) {
            System.out.println("Error saving expenses: " + e.getMessage());
        }
    }

    public static ArrayList<Expense> loadExpenses() {
        ArrayList<Expense> expenses = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(FILENAME))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                expenses.add(new Expense(parts[0], parts[1], Double.parseDouble(parts[2])));
            }
        } catch (IOException e) {
            System.out.println("Error loading expenses: " + e.getMessage());
        }
        return expenses;
    }
}

3. Main Tracker Class:

The main user interface where expenses can be added, viewed or the application can be exited.
import java.util.Scanner;

public class ExpenseTracker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Expense> expenses = ExpenseStorage.loadExpenses();

        while (true) {
            System.out.println("\nExpense Tracker Menu:");
            System.out.println("1. Add Expense");
            System.out.println("2. View Expenses");
            System.out.println("3. Exit");
            System.out.print("Enter your choice: ");
            int choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    System.out.print("Enter date (YYYY-MM-DD): ");
                    String date = scanner.next();
                    scanner.nextLine();  // Consume newline left over
                    System.out.print("Enter description: ");
                    String desc = scanner.nextLine();
                    System.out.print("Enter amount: ");
                    double amount = scanner.nextDouble();
                    expenses.add(new Expense(date, desc, amount));
                    ExpenseStorage.saveExpenses(expenses);
                    break;
                case 2:
                    for (Expense e : expenses) {
                        System.out.println(e);
                    }
                    break;
                case 3:
                    System.out.println("Goodbye!");
                    return;
                default:
                    System.out.println("Invalid choice. Please select from the menu.");
            }
        }
    }
}

Output:

Expense Tracker Menu:
1. Add Expense
2. View Expenses
3. Exit
Enter your choice: 1

Enter date (YYYY-MM-DD): 2023-06-15
Enter description: Groceries
Enter amount: 35.50

Expense Tracker Menu:
1. Add Expense
2. View Expenses
3. Exit
Enter your choice: 1

Enter date (YYYY-MM-DD): 2023-06-16
Enter description: Utilities
Enter amount: 80.25

Expense Tracker Menu:
1. Add Expense
2. View Expenses
3. Exit
Enter your choice: 2

Expense(date=2023-06-15, description=Groceries, amount=35.5)
Expense(date=2023-06-16, description=Utilities, amount=80.25)

Expense Tracker Menu:
1. Add Expense
2. View Expenses
3. Exit
Enter your choice: 3

Goodbye!

Conclusion

Building a basic Expense Tracker in Java offers invaluable insights into the world of application development, from handling data structures like ArrayLists to managing file operations for data persistence. As you become more adept, consider enhancing this application – maybe introduce expense categories, integrate a database, or even build a GUI using JavaFX or Swing. Dive deeper into Java, and the possibilities are virtually limitless!

Comments