Here is an example of an if-else statement:
if( windSpeed > 20 ) {
hoistSmallSail();
}
else {
hoistLargeSail();
}
The if-else statement allows the program to select one of two mutually exclusive paths of execution. In
this case, if the wind is strong, the program calls a method to hoist a small sail. Otherwise, the program calls a
method to hoist a large sail. By the way, you can tell that hoistSmallSail() and hoistLargeSail()
are methods because a pair of parentheses follows the name. A method is a named block of code, and we will
talk about methods when we discuss classes and objects in more detail later.
Here is the syntax of the if-else statement:
if(
)
else
If the conditional expression is true, statement_one will be executed. If the conditional statement is
false, statement_two will be executed. As before, statement_one and statement_two can be
compound statements, i.e., code blocks framed in curly braces.
for
Programs frequently must iterate or loop through a block of code repeatedly. Java has several control structures
for this purpose, and one of the most commonly used control structures of this type is the for loop.
Suppose we want to compute the average grade in a class of students.
Pages:
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201