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("-----");
}
}
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.