Java Arena
Step 2 of 5

Calling a method from a loop

A method call is a statement like any other, so it can go inside a loop. The method's lines are written once and run every time the loop comes round:

public class Main {
    public static void main(String[] args) {
        for (int round = 1; round <= 3; round++) {
            System.out.println("Round " + round);
            printDivider();
        }
    }

    public static void printDivider() {
        System.out.println("-----");
    }
}
Output
Round 1
-----
Round 2
-----
Round 3
-----

Methods also make a program easier to change. To make the divider longer, you change one line in printDivider, and every call prints the new one.

Your task

Challenge 1 of 3

Make main print the line three times, with a single call to printLine() inside a loop. The program prints:

==========
==========
==========

Challenge 2

Read how many cheers the crowd wants, and call cheer() that many times. For the input 3 the program prints:

Hip hip hooray!
Hip hip hooray!
Hip hip hooray!

Challenge 3

Write two methods: tick() prints tick and tock() prints tock. Then read a number of rounds, and in each round call tick() and then tock(). For the input 2 the program prints:

tick
tock
tick
tock