Comprehensive Project

This lesson is the final project for the Java tutorial, applying all knowledge points.

Project Overview

Build a command-line Todo List application that supports:

Data Model

JAVA
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Todo implements Serializable {
    private static final long serialVersionUID = 1L;
    
    public enum Priority { LOW, MEDIUM, HIGH }
    public enum Status { PENDING, COMPLETED }
    
    private int id;
    private String title;
    private String description;
    private Priority priority;
    private Status status;
    private LocalDateTime createdAt;
    private LocalDateTime completedAt;
    
    public Todo(int id, String title, String description, Priority priority) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.priority = priority;
        this.status = Status.PENDING;
        this.createdAt = LocalDateTime.now();
    }
    
    // Getters/Setters
    public int getId() { return id; }
    public String getTitle() { return title; }
    public String getDescription() { return description; }
    public Priority getPriority() { return priority; }
    public Status getStatus() { return status; }
    public LocalDateTime getCreatedAt() { return createdAt; }
    public LocalDateTime getCompletedAt() { return completedAt; }
    
    public void setStatus(Status status) {
        this.status = status;
        if (status == Status.COMPLETED) {
            this.completedAt = LocalDateTime.now();
        }
    }
    
    public boolean isCompleted() {
        return status == Status.COMPLETED;
    }
    
    @Override
    public String toString() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String statusIcon = isCompleted() ? "✅" : "⬜";
        String priorityIcon;
        switch (priority) {
            case HIGH: priorityIcon = "🔴"; break;
            case MEDIUM: priorityIcon = "🟡"; break;
            default: priorityIcon = "🟢"; break;
        }
        return String.format("%s %s [%d] %s (%s)", 
            statusIcon, priorityIcon, id, title, createdAt.format(formatter));
    }
}

Manager Class

JAVA
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class TodoManager {
    private List<Todo> todos;
    private int nextId;
    private static final String FILE_NAME = "todos.dat";
    
    public TodoManager() {
        this.todos = new ArrayList<>();
        this.nextId = 1;
        loadFromFile();
    }
    
    // Add todo
    public Todo addTodo(String title, String description, Todo.Priority priority) {
        Todo todo = new Todo(nextId++, title, description, priority);
        todos.add(todo);
        saveToFile();
        return todo;
    }
    
    // Complete todo
    public boolean completeTodo(int id) {
        Todo todo = findById(id);
        if (todo != null && !todo.isCompleted()) {
            todo.setStatus(Todo.Status.COMPLETED);
            saveToFile();
            return true;
        }
        return false;
    }
    
    // Delete todo
    public boolean deleteTodo(int id) {
        Todo todo = findById(id);
        if (todo != null) {
            todos.remove(todo);
            saveToFile();
            return true;
        }
        return false;
    }
    
    // Find todo
    public Todo findById(int id) {
        return todos.stream()
            .filter(t -> t.getId() == id)
            .findFirst()
            .orElse(null);
    }
    
    // Get all todos
    public List<Todo> getAllTodos() {
        return new ArrayList<>(todos);
    }
    
    // Get pending todos
    public List<Todo> getPendingTodos() {
        return todos.stream()
            .filter(t -> !t.isCompleted())
            .collect(Collectors.toList());
    }
    
    // Get completed todos
    public List<Todo> getCompletedTodos() {
        return todos.stream()
            .filter(Todo::isCompleted)
            .collect(Collectors.toList());
    }
    
    // Sort by priority
    public List<Todo> sortByPriority() {
        return todos.stream()
            .sorted((a, b) -> {
                int cmp = b.getPriority().compareTo(a.getPriority());
                return cmp != 0 ? cmp : a.getId() - b.getId();
            })
            .collect(Collectors.toList());
    }
    
    // Sort by creation date
    public List<Todo> sortByDate() {
        return todos.stream()
            .sorted(Comparator.comparing(Todo::getCreatedAt))
            .collect(Collectors.toList());
    }
    
    // Statistics
    public int getTotal() { return todos.size(); }
    public int getPendingCount() { return (int) todos.stream().filter(t -> !t.isCompleted()).count(); }
    public int getCompletedCount() { return (int) todos.stream().filter(Todo::isCompleted).count(); }
    
    // Save to file
    private void saveToFile() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
            oos.writeObject(todos);
            oos.writeInt(nextId);
        } catch (IOException e) {
            System.out.println("Save failed: " + e.getMessage());
        }
    }
    
    // Load from file
    @SuppressWarnings("unchecked")
    private void loadFromFile() {
        File file = new File(FILE_NAME);
        if (!file.exists()) return;
        
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
            todos = (List<Todo>) ois.readObject();
            nextId = ois.readInt();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("Load failed: " + e.getMessage());
        }
    }
}

Main Program

JAVA
import java.util.List;
import java.util.Scanner;

public class TodoApp {
    private static TodoManager manager = new TodoManager();
    private static Scanner scanner = new Scanner(System.in);
    
    public static void main(String[] args) {
        System.out.println("=== Todo List ===");
        
        int choice;
        do {
            showMenu();
            choice = getIntInput("Enter choice: ");
            
            switch (choice) {
                case 1: addTodo(); break;
                case 2: listTodos(); break;
                case 3: completeTodo(); break;
                case 4: deleteTodo(); break;
                case 5: showStatistics(); break;
                case 6: listByPriority(); break;
                case 0: System.out.println("Goodbye!"); break;
                default: System.out.println("Invalid choice");
            }
        } while (choice != 0);
        
        scanner.close();
    }
    
    private static void showMenu() {
        System.out.println("\n--- Menu ---");
        System.out.println("1. Add todo");
        System.out.println("2. View all todos");
        System.out.println("3. Mark complete");
        System.out.println("4. Delete todo");
        System.out.println("5. Statistics");
        System.out.println("6. Sort by priority");
        System.out.println("0. Exit");
    }
    
    private static void addTodo() {
        System.out.print("Title: ");
        String title = scanner.nextLine().trim();
        if (title.isEmpty()) {
            System.out.println("Title cannot be empty");
            return;
        }
        
        System.out.print("Description: ");
        String desc = scanner.nextLine().trim();
        
        System.out.println("Priority: 1-Low 2-Medium 3-High");
        int p = getIntInput("Choice: ");
        Todo.Priority priority;
        switch (p) {
            case 1: priority = Todo.Priority.LOW; break;
            case 3: priority = Todo.Priority.HIGH; break;
            default: priority = Todo.Priority.MEDIUM;
        }
        
        Todo todo = manager.addTodo(title, desc, priority);
        System.out.println("Added: " + todo);
    }
    
    private static void listTodos() {
        List<Todo> todos = manager.getAllTodos();
        if (todos.isEmpty()) {
            System.out.println("No todos found");
            return;
        }
        
        System.out.println("\n--- Todo List ---");
        for (Todo todo : todos) {
            System.out.println(todo);
        }
        System.out.printf("Total: %d (Pending: %d, Completed: %d)%n", 
            manager.getTotal(), manager.getPendingCount(), manager.getCompletedCount());
    }
    
    private static void completeTodo() {
        listTodos();
        int id = getIntInput("Enter ID to complete: ");
        if (manager.completeTodo(id)) {
            System.out.println("Marked as complete");
        } else {
            System.out.println("Invalid ID or already completed");
        }
    }
    
    private static void deleteTodo() {
        listTodos();
        int id = getIntInput("Enter ID to delete: ");
        if (manager.deleteTodo(id)) {
            System.out.println("Deleted");
        } else {
            System.out.println("Invalid ID");
        }
    }
    
    private static void showStatistics() {
        System.out.println("\n=== Statistics ===");
        System.out.println("Total: " + manager.getTotal());
        System.out.println("Pending: " + manager.getPendingCount());
        System.out.println("Completed: " + manager.getCompletedCount());
        double rate = manager.getTotal() > 0 ? 
            (double) manager.getCompletedCount() / manager.getTotal() * 100 : 0;
        System.out.printf("Completion rate: %.1f%%%n", rate);
    }
    
    private static void listByPriority() {
        List<Todo> todos = manager.sortByPriority();
        System.out.println("\n--- Sorted by Priority ---");
        for (Todo todo : todos) {
            System.out.println(todo);
        }
    }
    
    private static int getIntInput(String prompt) {
        System.out.print(prompt);
        while (!scanner.hasNextInt()) {
            System.out.print("Please enter a number: ");
            scanner.next();
        }
        int value = scanner.nextInt();
        scanner.nextLine();  // Consume newline
        return value;
    }
}

Example Output

TEXT
=== Todo List ===

--- Menu ---
1. Add todo
2. View all todos
3. Mark complete
4. Delete todo
5. Statistics
6. Sort by priority
0. Exit
Enter choice: 1
Title: Learn Java
Description: Complete Java tutorial lesson 32
Priority: 1-Low 2-Medium 3-High
Choice: 3
Added: ⬜ 🔴 [1] Learn Java (2026-06-24 14:30)

Enter choice: 2

--- Todo List ---
⬜ 🔴 [1] Learn Java (2026-06-24 14:30)
Total: 1 (Pending: 1, Completed: 0)

Knowledge Summary

Knowledge Application
Classes & Objects Todo, TodoManager class design
Encapsulation Private attributes, getters/setters
Enums Priority, Status enums
Collections List for todos, Stream operations
Exception handling File IO exception handling
File IO Serialization for save/load
Date/Time LocalDateTime for timestamps
Lambda Stream sorting, filtering
Generics List type safety

Extended Features

1. Filter by Date

JAVA
public List<Todo> getTodayTodos() {
    LocalDate today = LocalDate.now();
    return todos.stream()
        .filter(t -> t.getCreatedAt().toLocalDate().equals(today))
        .collect(Collectors.toList());
}

2. Search Function

JAVA
public List<Todo> search(String keyword) {
    String lower = keyword.toLowerCase();
    return todos.stream()
        .filter(t -> t.getTitle().toLowerCase().contains(lower) ||
                     t.getDescription().toLowerCase().contains(lower))
        .collect(Collectors.toList());
}

3. Export to Text

JAVA
public void exportToText(String filename) throws IOException {
    try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
        writer.println("=== Todo List Export ===");
        writer.println("Export time: " + LocalDateTime.now());
        writer.println();
        
        for (Todo todo : todos) {
            writer.println(todo);
            if (!todo.getDescription().isEmpty()) {
                writer.println("  " + todo.getDescription());
            }
            writer.println();
        }
    }
}

❓ Frequently Asked Questions

Q How to extend to a GUI application?
A Use JavaFX or Swing to implement a graphical interface.
Q How to support multiple users?
A Each user gets their own data file, or use database storage.
Q How to add reminder functionality?
A Use Timer/ScheduledExecutorService to check for due tasks.

📖 Summary

📝 Exercises

  1. Extend functionality: Add search and date filtering
  2. Data export: Support exporting to CSV format
  3. GUI version: Implement graphical interface with JavaFX

🎉 Congratulations on Completing the Java Tutorial!

Through 32 lessons, you have mastered:

Next steps to continue learning:

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏