GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java23 / 25

Final Project: Advanced Chatbot

Integrating all concepts into a complete chatbot

22.1 Learning objectives

By the end of this chapter, you should be able to:

  • integrate all the concepts learned so far (intents, entities, regular expressions, state management, and databases);
  • design a modular and extensible chatbot architecture;
  • implement a complete chatbot with multiple features;
  • handle errors and unexpected inputs gracefully;
  • test and validate the chatbot end to end.

22.2 Project overview

Advanced Chatbot Architecture.

Figure 22.1. Advanced Chatbot Architecture.

We will build a chatbot called Advanced TutorJavaBot that brings together:

  1. Natural language processing (regex, intents, entities)
  2. State management (state machine, slot filling)
  3. Data access (SQLite, safe parameterized queries)
  4. Smart response generation (pronoun transformation, response variety)
  5. User-friendly interface (console interaction with clear formatting)

22.3 System architecture

22.3.1 Chatbot layers

+--------------------+
|   User Interface   |  <-- Sends/receives messages
+--------------------+
|     Controller     |  <-- Manages conversation flow
+--------------------+
|  Message Processor |  <-- Classifies intents, extracts entities
+--------------------+
|   State Manager    |  <-- Maintains state and context
+--------------------+
|      Database      |  <-- Stores and queries records
+--------------------+

22.3.2 Class structure

ChatbotApp (main)
    ↓
ChatbotController
    ├─ MessageProcessor
    │   ├─ IntentClassifier
    │   └─ EntityExtractor
    ├─ StateManager
    │   └─ Slot
    ├─ DatabaseManager
    └─ ResponseGenerator

22.4 Complete implementation

All 8 source files for the chatbot package are available in ../examples/src/part3/chatbot/.

22.4.1 Step 1: Defining Intents

In the complete package, the Intent enum is defined inside IntentClassifier.java:

package chatbot;

/**
 * Intents supported by the chatbot.
 */
public enum Intent {
    GREETING,          // Greetings
    GOODBYE,           // Farewells
    THANKS,            // Gratitude
    HELP,              // Help request
    SEARCH_RESTAURANT, // Restaurant search
    BOOK_TABLE,        // Table reservation
    WEATHER,           // Weather inquiry
    JOKE,              // Joke request
    UNKNOWN            // Unknown intent
}

22.4.2 Step 2: Intent Classifier

Source file: IntentClassifier.java.

package chatbot;

import java.util.*;
import java.util.regex.*;

/**
 * Classifies user messages into intents.
 */
public class IntentClassifier {

    public enum Intent {
        GREETING,
        GOODBYE,
        THANKS,
        HELP,
        SEARCH_RESTAURANT,
        BOOK_TABLE,
        WEATHER,
        JOKE,
        UNKNOWN
    }

    private static final Map<Intent, List<Pattern>> PATTERNS = new EnumMap<>(Intent.class);

    static {
        PATTERNS.put(Intent.GREETING, Arrays.asList(
            Pattern.compile("\\b(hi|hello|good morning|good afternoon|good evening|hey|greetings)\\b", Pattern.CASE_INSENSITIVE)
        ));

        PATTERNS.put(Intent.GOODBYE, Arrays.asList(
            Pattern.compile("\\b(bye|goodbye|see you|farewell|later|take care)\\b", Pattern.CASE_INSENSITIVE)
        ));

        PATTERNS.put(Intent.THANKS, Arrays.asList(
            Pattern.compile("\\b(thanks|thank you|thx|appreciate|grateful)\\b", Pattern.CASE_INSENSITIVE)
        ));

        PATTERNS.put(Intent.HELP, Arrays.asList(
            Pattern.compile("\\b(help|what can you do|how to use|commands|options)\\b", Pattern.CASE_INSENSITIVE)
        ));

        PATTERNS.put(Intent.SEARCH_RESTAURANT, Arrays.asList(
            Pattern.compile("\\b(restaurant|eat|dinner|lunch|pizza|sushi|steak|steakhouse|diner|bistro|tavern|italian)\\b", Pattern.CASE_INSENSITIVE)
        ));

        PATTERNS.put(Intent.BOOK_TABLE, Arrays.asList(
            Pattern.compile("\\b(book|reserve|reservation|table|seat|make a reservation)\\b", Pattern.CASE_INSENSITIVE)
        ));

        PATTERNS.put(Intent.WEATHER, Arrays.asList(
            Pattern.compile("\\b(weather|forecast|rain|sunny|cold|hot|snow|temperature)\\b", Pattern.CASE_INSENSITIVE)
        ));

        PATTERNS.put(Intent.JOKE, Arrays.asList(
            Pattern.compile("\\b(joke|funny|laugh|humor|tell me a joke)\\b", Pattern.CASE_INSENSITIVE)
        ));
    }

    public static Intent classify(String message) {
        String normalized = message.toLowerCase().trim();

        for (Map.Entry<Intent, List<Pattern>> entry : PATTERNS.entrySet()) {
            for (Pattern pattern : entry.getValue()) {
                if (pattern.matcher(normalized).find()) {
                    return entry.getKey();
                }
            }
        }

        return Intent.UNKNOWN;
    }
}

22.4.3 Step 3: Entity Extractor

Source file: EntityExtractor.java.

package chatbot;

import java.util.*;
import java.util.regex.*;

/**
 * Extracts entities from user messages.
 */
public class EntityExtractor {

    public static class Entity {
        public final String type;
        public final String value;

        public Entity(String type, String value) {
            this.type = type;
            this.value = value;
        }

        @Override
        public String toString() {
            return String.format("%s:%s", type, value);
        }
    }

    private static final Map<String, Pattern> ENTITY_PATTERNS = new HashMap<>();

    static {
        ENTITY_PATTERNS.put("food", Pattern.compile(
            "\\b(pizza|sushi|steak|steakhouse|italian|japanese|diner|bistro|tavern|pub|bar)\\b",
            Pattern.CASE_INSENSITIVE
        ));

        ENTITY_PATTERNS.put("price", Pattern.compile(
            "\\b(cheap|medium|expensive|budget|affordable|moderate|luxury|gourmet|premium)\\b",
            Pattern.CASE_INSENSITIVE
        ));

        ENTITY_PATTERNS.put("area", Pattern.compile(
            "\\b(north|south|east|west|downtown|center|central)\\b",
            Pattern.CASE_INSENSITIVE
        ));

        ENTITY_PATTERNS.put("date", Pattern.compile(
            "\\b(today|tomorrow|yesterday|monday|tuesday|wednesday|thursday|friday|saturday|sunday)\\b",
            Pattern.CASE_INSENSITIVE
        ));

        ENTITY_PATTERNS.put("time", Pattern.compile(
            "(\\d{1,2}:\\d{2}|\\b\\d{1,2}\\s?(?:am|pm)\\b|\\bmorning\\b|\\bafternoon\\b|\\bevening\\b|\\bnight\\b|\\bnoon\\b|\\bmidnight\\b)",
            Pattern.CASE_INSENSITIVE
        ));

        ENTITY_PATTERNS.put("people", Pattern.compile(
            "\\b(\\d+)\\b", Pattern.CASE_INSENSITIVE
        ));

        ENTITY_PATTERNS.put("restaurant", Pattern.compile(
            "\\b(Pizza Place|Sushi Corner|Prime Steakhouse|Corner Diner|Italian Bistro|Downtown Tavern)\\b",
            Pattern.CASE_INSENSITIVE
        ));
    }

    public static List<Entity> extract(String message) {
        List<Entity> entities = new ArrayList<>();

        for (Map.Entry<String, Pattern> entry : ENTITY_PATTERNS.entrySet()) {
            Matcher matcher = entry.getValue().matcher(message);
            while (matcher.find()) {
                entities.add(new Entity(entry.getKey(), matcher.group()));
            }
        }

        return entities;
    }
}

22.4.4 Step 4: State Manager

Source file: StateManager.java.

package chatbot;

import java.util.*;

/**
 * Manages conversation state and slot collection.
 */
public class StateManager {

    public enum State {
        IDLE,             // Waiting for a command
        COLLECTING_SLOTS, // Collecting required information
        CONFIRMING,       // Confirming the request
        EXECUTING         // Executing the action
    }

    public static class Slot {
        public final String name;
        public final String question;
        public String value;

        public Slot(String name, String question) {
            this.name = name;
            this.question = question;
            this.value = null;
        }

        public boolean isFilled() {
            return value != null && !value.isEmpty();
        }
    }

    private State currentState;
    private IntentClassifier.Intent currentIntent;
    private List<Slot> slots;
    private int currentSlotIndex;
    private Map<String, String> context;

    public StateManager() {
        currentState = State.IDLE;
        slots = new ArrayList<>();
        context = new HashMap<>();
    }

    public void startConversation(IntentClassifier.Intent intent, List<Slot> requiredSlots) {
        currentIntent = intent;
        currentState = State.COLLECTING_SLOTS;
        slots = new ArrayList<>(requiredSlots);
        currentSlotIndex = 0;
        context.clear();
    }

    public void endConversation() {
        currentState = State.IDLE;
        currentIntent = null;
        slots.clear();
        currentSlotIndex = 0;
        context.clear();
    }

    public State getCurrentState() {
        return currentState;
    }

    public IntentClassifier.Intent getCurrentIntent() {
        return currentIntent;
    }

    public Slot getCurrentSlot() {
        if (currentSlotIndex < slots.size()) {
            return slots.get(currentSlotIndex);
        }
        return null;
    }

    public void fillCurrentSlot(String value) {
        if (currentSlotIndex < slots.size()) {
            slots.get(currentSlotIndex).value = value;
            context.put(slots.get(currentSlotIndex).name, value);
            currentSlotIndex++;
        }
    }

    public boolean allSlotsFilled() {
        for (Slot slot : slots) {
            if (!slot.isFilled()) {
                return false;
            }
        }
        return true;
    }

    public Map<String, String> getContext() {
        return new HashMap<>(context);
    }

    public void advanceState() {
        switch (currentState) {
            case COLLECTING_SLOTS:
                if (allSlotsFilled()) {
                    currentState = State.CONFIRMING;
                }
                break;
            case CONFIRMING:
                currentState = State.EXECUTING;
                break;
            case EXECUTING:
                currentState = State.IDLE;
                break;
            default:
                break;
        }
    }
}

22.4.5 Step 5: Response Generator

Source file: ResponseGenerator.java.

package chatbot;

import java.util.*;
import java.util.regex.*;

/**
 * Generates responses based on intent and context.
 */
public class ResponseGenerator {

    private static final Random RANDOM = new Random();

    // Responses for each intent
    private static final Map<IntentClassifier.Intent, List<String>> INTENT_RESPONSES =
        new EnumMap<>(IntentClassifier.Intent.class);

    static {
        INTENT_RESPONSES.put(IntentClassifier.Intent.GREETING, Arrays.asList(
            "Hello! How can I help you today?",
            "Hi there! I'm here to help.",
            "Good day! What do you need?"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.GOODBYE, Arrays.asList(
            "See you later! Have a great day!",
            "Goodbye! Come back anytime!",
            "Take care! See you soon!"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.THANKS, Arrays.asList(
            "You're welcome! Happy to help.",
            "No problem at all!",
            "My pleasure! That's what I'm here for."
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.HELP, Arrays.asList(
            "I can help you search for restaurants, book a table, check the weather, and tell jokes. " +
            "Try asking something like: 'Find an Italian restaurant' or 'Tell me a joke'.",
            "I'm a chatbot that can search restaurants, make table reservations, " +
            "give weather updates, and tell jokes. Try asking me a question!"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.WEATHER, Arrays.asList(
            "Today is sunny with pleasant temperatures.",
            "The weather is great for going out!",
            "Weather forecast: sunny with a few clouds."
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.JOKE, Arrays.asList(
            "Why do Java developers wear glasses? Because they don't C#! 😄",
            "What's a programmer's favorite data type? A boolean, because it's always true or false! 😂",
            "Why didn't the programmer leave the house? Because they hadn't made a commit yet! 🤣"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.UNKNOWN, Arrays.asList(
            "Sorry, I didn't understand. Could you repeat that or be more specific?",
            "I'm not sure what you mean. Try typing 'help'.",
            "I don't seem to know how to answer that. Would you like me to call a human?"
        ));
    }

    public static String generateRandomResponse(IntentClassifier.Intent intent) {
        List<String> responses = INTENT_RESPONSES.get(intent);
        return responses.get(RANDOM.nextInt(responses.size()));
    }

    public static String replacePronouns(String text) {
        Pattern pronounPattern = Pattern.compile("\\b(I|me|my|am|you|your|are)\\b", Pattern.CASE_INSENSITIVE);
        return pronounPattern.matcher(text).replaceAll(match -> {
            switch (match.group().toLowerCase()) {
                case "i":
                case "me":
                    return "you";
                case "my":
                    return "your";
                case "am":
                    return "are";
                case "you":
                    return "I";
                case "your":
                    return "my";
                case "are":
                    return "am";
                default:
                    return match.group();
            }
        });
    }

    public static String formatRestaurantResults(List<Map<String, Object>> results) {
        if (results.isEmpty()) {
            return "Sorry, I couldn't find any restaurants matching those criteria.";
        } else if (results.size() == 1) {
            Map<String, Object> r = results.get(0);
            return String.format("I found 1 restaurant: %s (%s, %s, rating: %.1f★)",
                r.get("name"), r.get("price_range"), r.get("area"), r.get("rating"));
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("I found %d restaurants:\n", results.size()));
            for (Map<String, Object> r : results) {
                sb.append(String.format("  - %s (%s, %.1f★)\n",
                    r.get("name"), r.get("area"), r.get("rating")));
            }
            return sb.toString();
        }
    }

    public static String formatBookingConfirmation(Map<String, String> context) {
        return String.format(
            "Reservation confirmed!\n" +
            "Restaurant: %s\n" +
            "Date: %s\n" +
            "Time: %s\n" +
            "People: %s",
            context.getOrDefault("restaurant", "?"),
            context.getOrDefault("date", "?"),
            context.getOrDefault("time", "?"),
            context.getOrDefault("people", "?")
        );
    }
}

22.4.6 Step 6: Message Processor

Source file: MessageProcessor.java.

package chatbot;

import java.util.*;

/**
 * Processes user messages and extracts structured information.
 */
public class MessageProcessor {

    private IntentClassifier intentClassifier;
    private EntityExtractor entityExtractor;
    private DatabaseManager databaseManager;

    public MessageProcessor(DatabaseManager dbManager) {
        this.intentClassifier = new IntentClassifier();
        this.entityExtractor = new EntityExtractor();
        this.databaseManager = dbManager;
    }

    public ProcessedMessage process(String message) {
        // Classify the intent
        IntentClassifier.Intent intent = IntentClassifier.classify(message);

        // Extract entities
        List<EntityExtractor.Entity> entities = EntityExtractor.extract(message);

        // Extract parameters
        Map<String, String> params = extractParameters(entities);

        return new ProcessedMessage(intent, entities, params);
    }

    private Map<String, String> extractParameters(List<EntityExtractor.Entity> entities) {
        Map<String, String> params = new HashMap<>();

        for (EntityExtractor.Entity entity : entities) {
            // Keep the first value found for each entity type
            if (!params.containsKey(entity.type)) {
                params.put(entity.type, entity.value);
            }
        }

        return params;
    }

    public static class ProcessedMessage {
        public final IntentClassifier.Intent intent;
        public final List<EntityExtractor.Entity> entities;
        public final Map<String, String> params;

        public ProcessedMessage(IntentClassifier.Intent intent,
                                List<EntityExtractor.Entity> entities,
                                Map<String, String> params) {
            this.intent = intent;
            this.entities = entities;
            this.params = params;
        }
    }
}

22.4.7 Step 7: Database Manager

Source file: DatabaseManager.java.

package chatbot;

import java.sql.*;
import java.util.*;

/**
 * Manages SQLite database connections and queries.
 */
public class DatabaseManager {

    private static final String DB_URL = "jdbc:sqlite:restaurants.db";

    public DatabaseManager() {
        initializeDatabase();
    }

    private void initializeDatabase() {
        try (Connection conn = DriverManager.getConnection(DB_URL);
             Statement stmt = conn.createStatement()) {

            stmt.execute("CREATE TABLE IF NOT EXISTS restaurants (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name TEXT NOT NULL," +
                "price_range TEXT CHECK(price_range IN ('cheap', 'medium', 'expensive'))," +
                "area TEXT CHECK(area IN ('north', 'south', 'east', 'west', 'downtown'))," +
                "rating REAL CHECK(rating >= 0 AND rating <= 5))");

            // Check whether sample data already exists
            ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM restaurants");
            if (rs.next() && rs.getInt(1) == 0) {
                stmt.executeUpdate("INSERT INTO restaurants (name, price_range, area, rating) VALUES " +
                    "('Pizza Place', 'medium', 'downtown', 4.5)," +
                    "('Sushi Corner', 'expensive', 'north', 4.8)," +
                    "('Prime Steakhouse', 'expensive', 'south', 4.7)," +
                    "('Corner Diner', 'cheap', 'east', 4.2)," +
                    "('Italian Bistro', 'medium', 'west', 4.6)," +
                    "('Downtown Tavern', 'cheap', 'downtown', 4.3)");
            }

        } catch (SQLException e) {
            System.err.println("Error initializing database: " + e.getMessage());
        }
    }

    public List<Map<String, Object>> searchRestaurants(Map<String, String> params) throws SQLException {
        List<Map<String, Object>> results = new ArrayList<>();

        StringBuilder sql = new StringBuilder("SELECT * FROM restaurants WHERE 1=1");
        List<String> values = new ArrayList<>();

        if (params.containsKey("food")) {
            sql.append(" AND name LIKE ?");
            values.add("%" + params.get("food") + "%");
        }
        if (params.containsKey("price")) {
            sql.append(" AND price_range = ?");
            values.add(params.get("price"));
        }
        if (params.containsKey("area")) {
            sql.append(" AND area = ?");
            values.add(params.get("area"));
        }

        sql.append(" ORDER BY rating DESC");

        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql.toString())) {

            for (int i = 0; i < values.size(); i++) {
                pstmt.setString(i + 1, values.get(i));
            }

            try (ResultSet rs = pstmt.executeQuery()) {
                ResultSetMetaData meta = rs.getMetaData();
                while (rs.next()) {
                    Map<String, Object> row = new HashMap<>();
                    for (int i = 1; i <= meta.getColumnCount(); i++) {
                        row.put(meta.getColumnName(i), rs.getObject(i));
                    }
                    results.add(row);
                }
            }
        }

        return results;
    }
}

22.4.8 Step 8: Main Controller

Source file: ChatbotController.java.

package chatbot;

import chatbot.StateManager.Slot;
import java.sql.SQLException;
import java.util.*;

/**
 * Main controller for the chatbot.
 */
public class ChatbotController {

    private StateManager stateManager;
    private MessageProcessor messageProcessor;
    private DatabaseManager databaseManager;

    public ChatbotController() {
        this.databaseManager = new DatabaseManager();
        this.messageProcessor = new MessageProcessor(databaseManager);
        this.stateManager = new StateManager();
    }

    public String handleMessage(String message) {
        MessageProcessor.ProcessedMessage processed = messageProcessor.process(message);
        IntentClassifier.Intent intent = processed.intent;

        // Check the current conversation state
        switch (stateManager.getCurrentState()) {
            case IDLE:
                return handleIdleState(message, intent, processed);

            case COLLECTING_SLOTS:
                return handleCollectingSlotsState(message, intent, processed);

            case CONFIRMING:
                return handleConfirmingState(message);

            case EXECUTING:
                return handleExecutingState(message);

            default:
                return ResponseGenerator.generateRandomResponse(IntentClassifier.Intent.UNKNOWN);
        }
    }

    private String handleIdleState(String message, IntentClassifier.Intent intent,
                                   MessageProcessor.ProcessedMessage processed) {
        switch (intent) {
            case GREETING:
            case GOODBYE:
            case THANKS:
            case HELP:
            case WEATHER:
            case JOKE:
                return ResponseGenerator.generateRandomResponse(intent);

            case SEARCH_RESTAURANT:
                try {
                    List<Map<String, Object>> results =
                        databaseManager.searchRestaurants(processed.params);
                    return ResponseGenerator.formatRestaurantResults(results);
                } catch (SQLException e) {
                    return "Error searching restaurants: " + e.getMessage();
                }

            case BOOK_TABLE:
                // Start the reservation flow
                List<Slot> slots = Arrays.asList(
                    new Slot("restaurant", "Which restaurant?"),
                    new Slot("date", "For what date?"),
                    new Slot("time", "What time?"),
                    new Slot("people", "For how many people?")
                );
                stateManager.startConversation(intent, slots);
                return stateManager.getCurrentSlot().question;

            case UNKNOWN:
            default:
                return ResponseGenerator.generateRandomResponse(intent);
        }
    }

    private String handleCollectingSlotsState(String message, IntentClassifier.Intent intent,
                                              MessageProcessor.ProcessedMessage processed) {
        Slot currentSlot = stateManager.getCurrentSlot();

        // Check whether the message fills the current slot
        String value = extractSlotValue(currentSlot.name, message, processed);

        if (value != null) {
            stateManager.fillCurrentSlot(value);

            if (stateManager.allSlotsFilled()) {
                stateManager.advanceState();
                return formatConfirmation();
            } else {
                return stateManager.getCurrentSlot().question;
            }
        }

        return "I didn't understand. " + currentSlot.question;
    }

    private String handleConfirmingState(String message) {
        String lower = message.toLowerCase();
        if (lower.contains("yes") || lower.contains("ok") || lower.contains("confirm")) {
            stateManager.advanceState();
            String confirmation = ResponseGenerator.formatBookingConfirmation(stateManager.getContext());
            stateManager.endConversation();
            return confirmation;
        } else if (lower.contains("no") || lower.contains("cancel")) {
            stateManager.endConversation();
            return "Reservation canceled. How else can I help you?";
        } else {
            return "Would you like to confirm or cancel? (yes/no)";
        }
    }

    private String handleExecutingState(String message) {
        stateManager.endConversation();
        return "Action completed! " + ResponseGenerator.generateRandomResponse(IntentClassifier.Intent.THANKS);
    }

    private String extractSlotValue(String slotName, String message,
                                    MessageProcessor.ProcessedMessage processed) {
        // Check extracted entities
        for (EntityExtractor.Entity entity : processed.entities) {
            if (entity.type.equals(slotName)) {
                return entity.value;
            }
        }

        // Check extracted parameters
        if (processed.params.containsKey(slotName)) {
            return processed.params.get(slotName);
        }

        // Fall back to direct extraction from the message
        String lower = message.toLowerCase();
        switch (slotName) {
            case "restaurant":
                if (lower.contains("pizza")) return "Pizza Place";
                if (lower.contains("sushi")) return "Sushi Corner";
                if (lower.contains("steak")) return "Prime Steakhouse";
                if (lower.contains("diner")) return "Corner Diner";
                if (lower.contains("italian") || lower.contains("bistro")) return "Italian Bistro";
                if (lower.contains("tavern") || lower.contains("bar")) return "Downtown Tavern";
                break;

            case "date":
                if (lower.contains("today")) return "today";
                if (lower.contains("tomorrow")) return "tomorrow";
                break;

            case "time":
                if (message.matches(".*\\d{1,2}:\\d{2}.*")) {
                    return message.replaceAll(".*(\\d{1,2}:\\d{2}).*", "$1");
                }
                break;

            case "people":
                if (message.matches(".*\\d+.*")) {
                    return message.replaceAll(".*(\\d+).*", "$1");
                }
                break;
        }

        return null;
    }

    private String formatConfirmation() {
        Map<String, String> context = stateManager.getContext();
        StringBuilder sb = new StringBuilder();
        sb.append("Please confirm your reservation:\n");
        for (Map.Entry<String, String> entry : context.entrySet()) {
            sb.append(String.format("  %s: %s\n", entry.getKey(), entry.getValue()));
        }
        sb.append("Confirm? (yes/no)");
        return sb.toString();
    }
}

22.4.9 Step 9: Main Application

Source file: ChatbotApp.java.

package chatbot;

import java.util.Scanner;

/**
 * Main entry point for the chatbot application.
 */
public class ChatbotApp {

    public static void main(String[] args) {
        ChatbotController controller = new ChatbotController();
        Scanner scanner = new Scanner(System.in);

        System.out.println("=== Advanced TutorJavaBot ===");
        System.out.println("Type 'exit' to quit.");
        System.out.println("Type 'help' to see available options.\n");

        while (true) {
            System.out.print("User: ");
            String input = scanner.nextLine();

            if (input.equalsIgnoreCase("exit")) {
                System.out.println("Bot: Goodbye!");
                break;
            }

            String response = controller.handleMessage(input);
            System.out.println("Bot: " + response);
            System.out.println();
        }

        scanner.close();
    }
}

22.5 Directory structure

examples/src/part3/chatbot/
├── ChatbotApp.java          // Main class
├── ChatbotController.java   // Controller
├── DatabaseManager.java     // Database manager
├── EntityExtractor.java     // Entity extractor
├── IntentClassifier.java    // Intent classifier
├── MessageProcessor.java    // Message processor
├── ResponseGenerator.java   // Response generator
└── StateManager.java        // State manager

22.6 Compiling and running

22.6.1 Step 1: Download the SQLite JDBC driver

Download the latest JAR file from: https://github.com/xerial/sqlite-jdbc/releases

Place sqlite-jdbc-<version>.jar in the examples/lib/ directory.

22.6.2 Step 2: Compile

From the examples/src/part3/ directory, run:

cd examples/src/part3
javac --release 21 -encoding UTF-8 -d out chatbot/*.java

22.6.3 Step 3: Run

On Windows (PowerShell):

java -cp "out;../../lib/sqlite-jdbc-*.jar" chatbot.ChatbotApp

Or on Linux/macOS:

java -cp "out:../../lib/sqlite-jdbc-*.jar" chatbot.ChatbotApp

22.7 Testing the chatbot

22.7.1 Basic tests

User: Hello
Bot: Hello! How can I help you today?

User: Help
Bot: I can help you search for restaurants, book a table, check the weather, and tell jokes. ...

User: Find an Italian restaurant
Bot: I found 1 restaurant: Italian Bistro (medium, west, rating: 4.6★)

User: Tell me a joke
Bot: Why do Java developers wear glasses? Because they don't C#! 😄

User: I want to book a table
Bot: Which restaurant?

User: Pizza Place
Bot: For what date?

User: tomorrow
Bot: What time?

User: 20:00
Bot: For how many people?

User: 4
Bot: Please confirm your reservation:
  Restaurant: Pizza Place
  Date: tomorrow
  Time: 20:00
  People: 4
Confirm? (yes/no)

User: yes
Bot: Reservation confirmed!
Restaurant: Pizza Place
Date: tomorrow
Time: 20:00
People: 4
Thank you for using our service!

22.8 Project evolution

In this final chapter, we integrated all the concepts from Part III:

  1. Intents and Entities (Chapter 3): Classification and extraction
  2. Regular Expressions (Chapter 2): Pattern matching and text processing
  3. State Management (Chapter 4): State machines and incremental slot filling
  4. Databases (Chapter 5): SQLite and safe parameterized queries
  5. Response Generation: Pronoun transformation and varied responses

The result is a complete chatbot that:

  • Understands user intents
  • Extracts specific information from messages
  • Maintains conversation context
  • Accesses real data from a database
  • Produces natural responses
  • Supports multiple features in one cohesive architecture

22.9 Verifiable practice

  1. Implement all classes in the chatbot package (examples/src/part3/chatbot/).
  2. Download the SQLite JDBC driver.
  3. Compile and run ChatbotApp.
  4. Test every feature:
    • Greetings
    • Restaurant search
    • Table reservation
    • Weather questions
    • Jokes
    • Help
  5. Test with unexpected or malformed messages.

Completion criteria:

  • All classes compile cleanly without errors
  • The chatbot responds accurately to every intent
  • The reservation flow works end to end
  • Database queries are safe against SQL injection
  • The code follows standard Java naming conventions

22.10 Challenges for further growth

  1. Add more intents: FAQ answers, real-time weather forecasts (via a REST API)
  2. Improve entity extraction: Use more advanced NLP libraries
  3. Add authentication: Implement a user login flow
  4. Store conversation history: Save chat transcripts in the database
  5. Build a graphical interface: Use JavaFX or Swing
  6. Add multi-language support: Internationalize prompts and patterns
  7. Add personalization: Save user preferences across sessions

Congratulations!

You have completed Part III of the book! You now have the skills to:

  • Build intelligent chatbots in Java
  • Process natural language text
  • Manage multi-turn conversation state
  • Connect to and query relational databases
  • Integrate all of these concepts into complete applications

The knowledge you gained here can be applied to:

  • Building virtual assistants
  • Developing automated customer support systems
  • Creating bots for messaging platforms and social media
  • Adding conversational interfaces to existing software
  • Exploring advanced AI and NLP technologies

Keep practicing and exploring—the world of chatbots and natural language processing is vast and exciting!

22.11 Additional resources

22.12 Summary of Part III

Part III of the book covered:

ChapterTopics
1Introduction to Chatbots, EchoBot, ELIZA, Personality
2Regular Expressions, Phrase Extraction, Pronoun Transformation
3Intents and Entities, Classification, Extraction, Similarity
4Stateful Chatbots, State Machines, Slot Filling, Negation
5Database Integration, SQL, JDBC, SQLite
6Final Project — Integrated Advanced Chatbot

You are now ready to build your own chatbots in Java!