- Learning Java by Building Android Games
- John Horton
- 138字
- 2021-07-23 19:02:27
Combining different control flow blocks
And you might have been able to guess that we can combine any of the decision-making tools like if
, else
, and switch
within our while
loops and all the rest of the loops too. For example:
int x = 0; int tooBig = 10; while(true){ x++; // I am going to get mighty big! if(x == tooBig){ break; } // No you're not // code reaches here only until x = 10 }
It would be simple to go on for many more pages demonstrating the versatility of control flow structures but at some point, we want to get back to finishing the game.
Now we are confident with if
and else
, let's have a look at one more concept to do with loops. So here is one last concept combined with loops.
Continue...
The continue keyword acts in a similar way to break
- that we learned about in the previous chapter- up to a point. The continue
keyword will break out of the loop body but will also check the condition expression afterward so the loop could run again. An example will help.
int x = 0; int tooBig = 10; int tooBigToPrint = 5; while(true){ x++; // I am going to get mighty big! if(x == tooBig){ break; } // No your not haha. // code reaches here only until x = 10 if(x >= tooBigToPrint){ // No more printing but keep looping continue; } // code reaches here only until x = 5 // Print out x }
The continue
keyword can be used in all the loops just as the break
keyword can.