Loops

Figure 159. Why loops? Slide presentation

Objective: Execute the same statement multiple times.

Solution: Copy / paste the statement in question:

System.out.println("Do not copy!");
System.out.println("Do not copy!");
System.out.println("Do not copy!");
System.out.println("Do not copy!");

Problem: Only works if number of repetitions is known at compile time.


Figure 160. Arbitrary number of repetitions Slide presentation
System.out.print("Enter desired number of repetitions: ");
final int repetitions = scan.nextInt();
switch(repetitions) {
    case 5: System.out.println("Do not copy!");
    case 4: System.out.println("Do not copy!");
    case 3: System.out.println("Do not copy!");
    case 2: System.out.println("Do not copy!");
    case 1: System.out.println("Do not copy!");   }

Limited and clumsy workaround.