- Learning Java by Building Android Games
- John Horton
- 303字
- 2021-07-23 19:02:26
Loops
It would be completely reasonable to ask what loops have to do with programming. But they are exactly what the name implies. They are a way of repeating the same part of the code more than once or looping over the same part of code although potentially for a different outcome each time.
This can simply mean doing the same thing until the code being looped over (iterated) prompts the loop to end. It could be a predetermined number of iterations as specified by the loop code itself or it might be until a predetermined situation or condition is met. Or it could be a combination of more than one of these things. Along with if
, else
, and switch
, which we will learn about in the next chapter, loops are part of the Java control flow statements.
Here we will learn how to repeatedly execute portions of our code in a controlled and precise way by looking at diverse types of loops in Java. Think about the conundrum of drawing all the grid lines in the Sub' Hunter game. Repeating the same code over and over could be very useful for drawing dozens of lines on the screen without writing dozens of repetitive lines of code.
The types of loops include while loops, do while loops and for loops. We will also learn the most appropriate situations to use the different types of loops.
We will look at all the major types of loops that Java offers us to control our code and we will use some of them to implement a working mini-app to make sure we understand them completely, then we can add some code to take advantage of loops in the Sub' Hunter game. Let us look at the first simplest loop type in Java called the while
loop.