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

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, and for;
  • define a clear stopping condition;
  • use counters and accumulators;
  • apply break and continue without obscuring control flow.

4.2 Choosing the loop

Anatomy of a loop with a stopping condition.

Figure 4.1. Anatomy of a loop with a stopping condition.

Use:

  • while when the number of repetitions is unknown;
  • do-while when the block must execute at least once;
  • for when there is a well-defined range or counter;
  • for-each to 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

Comic: the infinite loop.

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:

  1. what state changes on each iteration?
  2. when does the repetition stop?
  3. has the empty case been handled?
  4. 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 n2n^2. 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:

  1. an optional limit of five messages;
  2. a counter for unknown commands;
  3. the total number of typed characters, excluding exit.

Test cases:

SequenceExpected result
hi, exitone recorded message
blank line, exitzero messages
five messagesexits upon reaching the limit
EXITnormal termination

Classic mistake

A while loop in which no variable modifies the condition can cause an infinite loop. Verify the stopping condition before running your code.