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

Answers and Hints

Consult only after attempting the activities yourself

This appendix presents verification criteria and possible approaches. Your solution may use different names or structures and still be correct as long as it respects the proposed contract. Complete programs are available in examples/src.

How to use the answers without missing the opportunity to practice.

Figure 1. How to use the answers without missing the opportunity to practice.

First Steps

The public class and the file must share the exact same name. The right sequence is:

javac ClassName.java
java ClassName

If the compiler reports ';' expected, check the indicated statement as well as the line right before it.

Variables, Types, and Input

One possible solution uses String for name and city and int for hours. The four-week total is weeklyHours * 4. Apply strip() to text inputs and parse numbers with Integer.parseInt(scanner.nextLine()).

Conditionals

The classification must check the boundaries in order:

if (hours < 3) {
    return "starter pace";
} else if (hours <= 6) {
    return "steady pace";
}
return "intensive pace";

The value 3 belongs to the steady pace range; so does 6.

Loops

Keep separate counters for valid messages, unknown messages, and characters. Update them only after rejecting empty input and before checking the maximum limit.

Methods

One possible implementation for checking a known command:

static boolean isKnownCommand(String input) {
    return switch (normalizeCommand(input)) {
        case "hi", "help", "tip", "exit" -> true;
        default -> false;
    };
}

The method should not print anything; it only returns a decision.

Arrays

For the array {30, 40, 20, 50, 10}, the total is 150, the average is 30.0, the maximum is 50, and the minimum is 10. Before initializing maximum and minimum with the first element, reject length == 0.

Lists

To keep only the last ten items:

history.add(message);
if (history.size() > 10) {
    history.remove(0);
}

To query the last three, compute Math.max(0, size - 3) and return a copy of that subrange.

Classes and Objects

totalMessages() should query the list rather than maintaining a second counter that could fall out of sync. The constructor rejects null and isBlank(). List.copyOf protects the internal structure.

Exceptions and Files

Catch NumberFormatException inside the input loop. Propagate IOException from the persistence method and catch it in the console application. That way, each layer decides only the errors it knows how to present.

Integrated Chatbot

The history lookup must occur before recording the interaction. The exit command is handled by the outer loop. Empty inputs never reach the recording method.

Object-Oriented Design

The extraction is right when History can be tested without Scanner and CommandProcessor knows nothing about files or the console. The behavior observed by the user must remain unchanged.

Inheritance

Warning extends BotMessage calls super("warning") and overrides text(). If warnings only need to hold a variable message, composition can be simpler than creating many subclasses.

Interfaces and Polymorphism

AboutCommand implements Command and is added to the collection. The process method must not gain another if or case.

Generics and Collections

Use putIfAbsent to detect duplicate keys. Normalize the key during both registration and lookup. List.copyOf and Map.copyOf are well suited for exposing immutable views.

Testing and Refactoring

Make a test fail by temporarily changing the expected value. The message should identify the description, expected value, and actual value. Restore the test before moving on. A refactoring is complete only when all cases pass again.

Final Project

Before looking at the reference implementation, verify:

  • all required commands work;
  • empty input does not enter the history;
  • history and counter share the same definition of an interaction;
  • duplicate commands are rejected;
  • file failures are handled gracefully;
  • examples compile with --release 21;
  • adding a new command requires no changes to the central processor.

Compare your solution with Chapter16Project.java and note at least one decision you would keep and one you would change.