Java Reference
In-Depth Information
A fencepost loop executes a “loop-and-a-half” by execut-
ing part of a loop's body once before the loop begins.
Boolean variables (sometimes called “flags”) can store
Boolean values and can be used as loop tests.
A sentinel loop is a kind of fencepost loop that repeatedly
processes input until it is passed a particular value, but
does not process the special value.
A complex Boolean expression can be negated using a
set of rules known as De Morgan's Laws, in which each
sub-expression is negated and all AND and OR operations
are swapped.
The boolean primitive type represents logical values of
either true or false . Boolean expressions are used as
tests in if statements and loops. Boolean expressions can
use relational operators such as < or != as well as
logical operators such as && or ! .
A robust program checks for errors in user input. Better
robustness can be achieved by looping and reprompting
the user to enter input when he or she types bad input.
The Scanner class has methods like hasNextInt that
you can use to “look ahead” for valid input.
Complex Boolean tests with logical operators such as &&
or || are evaluated lazily: If the overall result is clear
from evaluating the first part of the expression, later parts
are not evaluated. This is called short-circuited
evaluation.
Assertions are logical statements about a particular point in a
program. Assertions are useful for proving properties about
how a program will execute. Two useful types of assertions
are preconditions and postconditions, which are claims about
what will be true before and after a method executes.
Self-Check Problems
Section 5.1: The while Loop
1. For each of the following while loops, state how many times the loop will execute its body. Remember that “zero,”
“infinity,” and “unknown” are legal answers. Also, what is the output of the code in each case?
a. int x = 1;
while (x < 100) {
System.out.print(x + " ");
x += 10;
}
b. int max = 10;
while (max < 10) {
System.out.println("count down: " + max);
max--;
}
c. int x = 250;
while (x % 3 != 0) {
System.out.println(x);
}
 
Search WWH ::




Custom Search