Java Reference
In-Depth Information
2. A for statement contains three parts. The first part is executed once at the beginning.
Then the condition in the middle is checked. Similar to an if statement, the body is
executed when the condition is true. The third part of a for statement is executed
after every execution of the body of the loop. The first part of a for loop can define
and initialize multiple variables of the same type. The variables must be separated by
commas. Similarly, the third part of a for loop can perform several actions that are
separated by commas. Each of the parts of a for loop can be missing. If the middle
of a for loop is missing, the Boolean value true is used.
3. The operation i++ means use the current value of the variable i in the calculations
andthenincrement i by 1. Conversely, ++i means increment the variable i by 1 and
then use the new value of the variable i in the expression.
4. Do not forget to add a semicolon after a do -while statement. This is the only loop
that requires a semicolon at the end.
5. The continue statement can be used inside any of the three loops. It forces Java to
skip the rest of the body of the loop and start a new iteration. In a for loop, the
statement will make the program jump to the third part of the for loop. For a while
and do-while statement, the program jumps to the condition. If the condition is true,
then the body is executed again. If it is not, then the loop is terminated.
6. The break statement can be used in any kind of a loop or a switch construct. The
statement instructs Java to jump to the line that is immediately after the body of the
7. The counter variable should usually not be modified inside the body of a for state-
ment. It should only be modified in the third part of the for statement, which is
executed immediately after the body of the for statement.
8. Always create a block for a loop by inserting opening and closing braces. Although
Java allows the body of a loop to be a single statement without surrounding braces,
doing so is bad programming practice.
9. The operator % is used to calculate the remainder of dividing two integers.
3.9 Exercises
1. Improve the multiplication game from the previous chapter. We will randomly ask the
player to either add, multiply, or subtract one-digit numbers (we skip division because
the result of dividing two numbers is not an integer). The game should ask 10 math
questions and record the answers. At the end, the game should tell the player how
well they did, that is, how many questions they answered correctly.
2. What is the result of executing the following statements?
int i=5;
System. out . println ( i ) ;
Compile and run the program to check your answer.
Search WWH ::

Custom Search