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

Console Chatbot

Integrating the fundamentals into a complete application

10.1 Learning objectives

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

  • integrate input, conditionals, loops, methods, lists, and exceptions;
  • define each command’s contract clearly;
  • separate console interaction from chatbot rules;
  • maintain consistent semantics for conversation history.

10.2 Command contract

Main flow of the console chatbot.

Figure 10.1. Main flow of the console chatbot.

In this version:

  • hi: introduces the bot;
  • help: lists commands;
  • tip: shows a Java tip;
  • history: displays previous interactions;
  • exit: ends the conversation.

Blank messages are not added to the history. The history and exit commands are not recorded either. Each normal interaction appends two lines: one from the user and one from the bot.

10.3 Integrated implementation

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;

public class Chapter10Chatbot {
    private final String name;
    private final List<String> history = new ArrayList<>();

    public Chapter10Chatbot(String name) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("Name is required.");
        }
        this.name = name.strip();
    }

    private static String normalize(String text) {
        if (text == null) {
            return "";
        }
        return text.strip().toLowerCase(Locale.ROOT);
    }

    public String respond(String input) {
        String command = normalize(input);

        if (command.isBlank()) {
            return "Enter a message.";
        }
        if (command.equals("history")) {
            return history.isEmpty()
                    ? "No history."
                    : String.join(System.lineSeparator(), history);
        }

        String reply = switch (command) {
            case "hi" -> "Hello! I am " + name + ".";
            case "help" -> "Commands: hi, help, tip, history, and exit.";
            case "tip" -> "Compile and test after every small change.";
            default -> "I did not understand. Type help.";
        };

        history.add("USER: " + input.strip());
        history.add("BOT: " + reply);
        return reply;
    }

    public int totalInteractions() {
        return history.size() / 2;
    }

    public static void main(String[] args) {
        Chapter10Chatbot bot = new Chapter10Chatbot("TutorJavaBot");

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Type help to see the commands.");

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

                if (normalize(input).equals("exit")) {
                    break;
                }

                System.out.println("Bot: " + bot.respond(input));
            }
        }

        System.out.println("Recorded interactions: " + bot.totalInteractions());
        System.out.println("Bot: See you soon!");
    }
}

10.4 Separation of responsibilities

The class still holds both the console interface and the domain rules, but the boundary is already clear:

  • main: reads from and writes to the terminal;
  • normalize: standardizes commands;
  • respond: applies response rules;
  • history: holds the conversation state.

In Part II of this book, these responsibilities will be split across smaller classes and contracts.

10.5 Project evolution: version 10

This version wraps up the fundamentals track. The program compiles, runs until exit, guides invalid inputs, and maintains a well-defined conversation history.

The complete example is in examples/src/Chapter10Chatbot.java.

10.6 Manual test script

ScenarioSequenceResult
normal flowhi, tip, exittwo interactions
unknown commandxyzguidance to type help
empty inputEntercorrection message, nothing recorded
historyhi, historytwo lines from the previous interaction
casing and spacesHELPlist of commands

10.7 Verifiable practice

  1. Show only the last six lines of history.
  2. Add the about command.
  3. Save the history upon exiting.
  4. Avoid duplicating the command list across different methods.

Checkpoint

Keep this working version. The upcoming chapters will reorganize the internal structure without changing the contract observed by the user.