← Вернуться к курсу: Java from scratch

Final project: console expense tracker

Видео скоро появится

You have reached the end of the course. In eight weeks you went from installing the JDK to mastering classes, inheritance, exceptions, collections, streams and files. Now you will put it all together in a project of your own: a personal expense tracker that runs in the console, saves its data in a CSV file and offers reports. It is a small but complete program, with the structure of a real application: data model, logic, persistence and user interface kept separate.

Requirements

  • A looping menu with Scanner: 1) add expense, 2) list expenses, 3) total per category, 4) largest expense, 5) delete an expense by number, 0) quit.
  • An expense has a date (LocalDate), a description, a positive amount and a category (an enum with at least FOOD, TRANSPORT, HOME and OTHER). It must be a record.
  • Data is saved in expenses.csv on exit (or after each change) and loaded on start. If the file does not exist, start with an empty list; a malformed line is skipped with a warning.
  • All user input is validated: a non-numeric or negative amount, an unknown category or a delete number out of range shows a message and returns to the menu without breaking the program.
  • Reports use streams (groupingBy, sum, max).
  • Split the code into at least three classes: Expense (model), ExpenseStore (loads and saves with NIO) and Main (menu).

Reference skeleton

This is a skeleton that already works and covers the core: model, persistence and a reduced menu. Read it carefully, run it and then extend it until it meets all the requirements. It is not a closed solution: deletion, the largest expense and several validations are missing, and they are your job. To run it as a single file save it as Main.java and use java Main.java.

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        ExpenseStore store = new ExpenseStore(Path.of("expenses.csv"));
        List<Expense> expenses = store.load();
        Scanner in = new Scanner(System.in);

        while (true) {
            System.out.println("\n1) Add  2) List  3) Totals  0) Quit");
            if (!in.hasNextLine()) break;
            String option = in.nextLine().trim();

            if (option.equals("0")) {
                break;
            } else if (option.equals("1")) {
                try {
                    System.out.print("Description: ");
                    String description = in.nextLine().trim();
                    System.out.print("Amount: ");
                    double amount = Double.parseDouble(in.nextLine().trim());
                    System.out.print("Category " + java.util.Arrays.toString(Category.values()) + ": ");
                    Category category = Category.valueOf(in.nextLine().trim().toUpperCase());
                    expenses.add(new Expense(LocalDate.now(), description, amount, category));
                    store.save(expenses);
                    System.out.println("Saved.");
                } catch (IllegalArgumentException e) {      // also NumberFormatException
                    System.out.println("Invalid data: " + e.getMessage());
                }
            } else if (option.equals("2")) {
                for (int i = 0; i < expenses.size(); i++) {
                    System.out.println((i + 1) + ". " + expenses.get(i));
                }
            } else if (option.equals("3")) {
                Map<Category, Double> totals = expenses.stream().collect(
                    Collectors.groupingBy(Expense::category, () -> new EnumMap<>(Category.class),
                                          Collectors.summingDouble(Expense::amount)));
                totals.forEach((c, t) -> System.out.printf("%s: %.2f%n", c, t));
            } else {
                System.out.println("Unknown option");
            }
        }
        System.out.println("Bye");
    }
}

enum Category { FOOD, TRANSPORT, HOME, OTHER }

record Expense(LocalDate date, String description, double amount, Category category) {
    Expense {
        if (description == null || description.isBlank())
            throw new IllegalArgumentException("description is required");
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
    }

    String toCsv() {
        return date + ";" + description.replace(";", ",") + ";" + amount + ";" + category;
    }

    static Expense fromCsv(String line) {
        String[] p = line.split(";");
        if (p.length != 4) throw new IllegalArgumentException("bad line");
        return new Expense(LocalDate.parse(p[0]), p[1], Double.parseDouble(p[2]),
                           Category.valueOf(p[3]));
    }

    @Override
    public String toString() {
        return String.format("%s | %-15s | %8.2f | %s", date, description, amount, category);
    }
}

class ExpenseStore {
    private final Path file;

    ExpenseStore(Path file) { this.file = file; }

    List<Expense> load() {
        List<Expense> result = new ArrayList<>();
        if (!Files.exists(file)) return result;
        try {
            for (String line : Files.readAllLines(file)) {
                try {
                    result.add(Expense.fromCsv(line));
                } catch (RuntimeException e) {          // includes DateTimeParseException
                    System.out.println("Skipped bad line: " + line);
                }
            }
        } catch (IOException e) {
            System.out.println("Could not read file: " + e.getMessage());
        }
        return result;
    }

    void save(List<Expense> expenses) {
        try {
            Files.write(file, expenses.stream().map(Expense::toCsv).toList());
        } catch (IOException e) {
            System.out.println("Could not save: " + e.getMessage());
        }
    }
}

This is how the data file produced by the skeleton looks (one line per expense, fields separated by semicolons). You can create one by hand to test loading, and include a corrupt line on purpose to check that it is skipped with a warning.

text
2026-11-23;Coffee;3.5;FOOD
2026-11-23;Taxi;12.0;TRANSPORT
oops

Suggested steps and completion criteria

  • Step 1: run the skeleton, add two or three expenses, quit, come back and check that they load.
  • Step 2: add option 4 (largest expense) with a stream and max, using Optional correctly when the list is empty.
  • Step 3: add option 5 (delete): validate that the number is between 1 and the size, use remove(int) and save.
  • Step 4: let the user optionally enter the date (LocalDate.parse) and handle a wrong format.
  • Step 5: add a report for the current month that filters by date with streams.
  • Criteria: it compiles without warnings; no strange user text makes the program end with an exception; data survives between runs; there are at least three classes and a record; you used at least one stream, one enum and a try-with-resources or a try/catch with finally; the code has clear names and short methods.

When you finish, review your code as someone else would: is it understandable without explanations? Are there methods over 20 lines that could be split? Do you repeat logic in two places? That review exercise is a professional skill. As next steps, you can explore Maven or Gradle to manage projects, JUnit to write automated tests, and then a framework such as Spring Boot to create web services. Everything you build on top rests on what you already know. Congratulations on completing the course.

Проверьте себя

Вопрос 1 из 7

Which structure is the most suitable for a total per category?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← Назад