Loops

Figure 191. Why loops? Slide presentation Create comment in forum

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 192. Arbitrary number of repetitions Slide presentation Create comment in forum
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.