Loops

Figure 167. Why loops? Slide presentation

Objective: Execute the same statement multiple times.

Solution: Copy / paste the statement in question:

IO.println("Do not copy!");
IO.println("Do not copy!");
IO.println("Do not copy!");
IO.println("Do not copy!");

Problem: Desired number of repetitions must be known at compile time.


Figure 168. Number of repetitions given by user input Slide presentation
System.out.print("Enter desired number of repetitions: ");
final int repetitions = scan.nextInt();

switch(repetitions) {  // Employing fall-through
    case 5: IO.println("Do not copy!");
    case 4: IO.println("Do not copy!");
    case 3: IO.println("Do not copy!");
    case 2: IO.println("Do not copy!");
    case 1: IO.println("Do not copy!");
}

Limited and clumsy workaround.