When you know how many times you want to repeat a block of code, use a FOR-LOOP.

for loop java

THEORY

This is how you have to program it:

java for loop

remember in Java it is usual to count from 0

Instead of saying, play 5 times, do you say play from 0 until 4, which is 5 times, if you move in steps of one.

EXTRA INFO

If you move with bigger steps you don’t do 5 repetitions.

e.g. in steps of two: you can do 3 repetitions

example

This is how it looks in code, if you want to play a loop that prints 5 times the sentence WHAT ARE THOOSEE!

DON’t DO IT LIKE THIS YOU GET AN ERROR!

void start () {
	for (0; 4; 1) {
		System.out.println("WHAT ARE THOOSEE!");
	}
}

Or this:

void start () {
	int i = 0;
	for (i; i <= 4; i=i+1) {
		System.out.println("WHAT ARE THOOSEE!");
	}
}

DO IT LIKE THIS!

void start () {
	int i;
	for (i = 0; i <= 4; i=i+1) {
		System.out.println("WHAT ARE THOOSEE!");
	}
}

You can optimise the code, this is how people commonly use a for-loop:

void start () {
	for (int i = 0; i <= 4; i++) {
		System.out.println("WHAT ARE THOOSEE!");
	}
}

so instead of:

  • declaring the variable i first, and then initialising i,
    int i;
    for (i = 0;....

    in the for-loop you can do all at ones.

    for (int i = 0;....
  • This code
    i = i + 1;

    is the same as this code

    i++;