Loops
Keeping the conversation active with clear stopping criteria
4.1 Learning objectives
By the end of this chapter, you should be able to:
- choose between
while,do-while, andfor; - define a clear stopping condition;
- use counters and accumulators;
- apply
breakandcontinuewithout obscuring control flow.
4.2 Choosing the loop

Figure 4.1. Anatomy of a loop with a stopping condition.
Use:
whilewhen the number of repetitions is unknown;do-whilewhen the block must execute at least once;forwhen there is a well-defined range or counter;for-eachto iterate through all elements of a structure.
for (int attempt = 1; attempt <= 3; attempt++) {
System.out.println("Attempt " + attempt);
}
4.3 Looping chatbot
import java.util.Scanner;
public class Chapter04Loops {
public static void main(String[] args) {
int totalMessages = 0;
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
System.out.print("You: ");
String message = scanner.nextLine().strip();
if (message.equalsIgnoreCase("exit")) {
break;
}
if (message.isBlank()) {
System.out.println("Bot: Enter a message.");
continue;
}
totalMessages++;
System.out.println("Bot: Received -> " + message);
}
}
System.out.println("Recorded messages: " + totalMessages);
}
}
The stopping condition is explicit: the exit command executes break. Blank inputs use continue and are not counted.
4.4 Counters and accumulators

Figure 4.2. Comic: the infinite loop.
A counter tracks how many times something happened. An accumulator aggregates values, such as the total number of characters:
int totalMessages = 0;
int totalCharacters = 0;
totalMessages++;
totalCharacters += message.length();
Before writing a loop, answer:
- what state changes on each iteration?
- when does the repetition stop?
- has the empty case been handled?
- is there any risk of accessing an invalid position?
4.5 Nested loops
Nested loops are useful for tables and matrices, but they multiply the number of iterations. For two loops iterating over n elements, the work can grow roughly like . First write a correct solution; then evaluate whether the data volume requires a different structure.
4.6 Project evolution: version 4
The chatbot stays active until it receives exit, rejects blank messages, and displays how many valid messages were received.
The complete example is in examples/src/Chapter04Loops.java.
4.7 Verifiable practice
Add:
- an optional limit of five messages;
- a counter for unknown commands;
- the total number of typed characters, excluding
exit.
Test cases:
| Sequence | Expected result |
|---|---|
hi, exit | one recorded message |
blank line, exit | zero messages |
| five messages | exits upon reaching the limit |
EXIT | normal termination |
Classic mistake
A
whileloop in which no variable modifies the condition can cause an infinite loop. Verify the stopping condition before running your code.