Java Reference
In-Depth Information
< Day Day Up >
Puzzle 28: Looper
This puzzle and the five that follow turn the tables on you. Instead of showing some code and
asking what it does, they make
you
write the code, albeit in small amounts. These puzzles are called
loopers
. You will be shown a loop that looks as though it ought to terminate quickly, and it will be
your job to come up with a variable declaration that makes it loop indefinitely, when placed
immediately above the loop. For example, consider this
for
loop:
for (int i = start; i <= start + 1; i++) {
}
It looks as though it should run for only two iterations, but it can be made to loop indefinitely by
taking advantage of the overflow behavior illustrated in
Puzzle 26
. The following declaration does
the trick:
int start = Integer.MAX_VALUE - 1;
Now it's your turn. What declaration turns this loop into an infinite loop?
while (i == i + 1) {
}
Solution 28: Looper
Looking at the
while
loop, it really seems as though it ought to terminate immediately. A number is
never equal to itself plus 1, right? Well, what if the number is infinity? Java mandates the use of
IEEE 754 floating-point arithmetic
[IEEE-754]
, which lets you represent infinity as a
double
or
float
. As we learned in school, infinity plus 1 is still infinity. If
i
is initialized to infinity before the
loop starts, the termination test (
i == i + 1
) evaluates to
true
, and the loop never terminates.
You can initialize
i
with any floating-point arithmetic expression that evaluates to infinity; for
Search WWH ::
Custom Search