Java Lesson 5 – Loops
A cool feature in many programming languages is the ability to repeat code over and over. A common use for loops can be found in games. Games have an infinite loop that updates the game with new information, clears the screen, then redraws the game components using new information.
There are three different types of loops in Java. These consist of the for loop, the while loop, and the do-while loop.
The For loop
The for loop is used to execute a block of code a set number of times. A practical example may be that the player wants to add 50 things to his inventory. Do you really want to have to write 50 lines of code to do that? You could write 50 lines of code in 4 lines.
for(int i = 0; i < 50; i++)
{
// code to add an item to inventory
}
The line that is probably confusing the fun nuggets out of you is the first line. Well, to start a for loop, you type the word ‘for’ followed by a set of parentheses. Inside the parentheses, you need three tidbits of information. You need to specify where you want the loop begin counting from. You will almost always want to begin from 0. We do this by declaring a temporary variable for this loop. This variable won’t be recognized outside the loop. We are creating an int and simultaneously set it to zero. The loop uses this variable as a counter or a stopwatch so to speak. Second, we tell the loop how far we would like to loop for using ‘i’. This is saying that we will continue counting until ‘I’ reaches 50 or higher. So as long as ‘I’ is less than 50, continue looping. Lastly, we specify the amount we want to increment our loop variable after each pass of the loop. ‘++’ is shorthand notation for “add one to this number.”
Notice how our three bits of information are separated by semi-colons. Think of semi-colons as the Java equivalent of periods at the end of sentences.
Loops will continue in the next lesson.