Java Reference

In-Depth Information

then trying to compile it and debug it. Waiting to compile until the program is

done may mean seeing dozens (literally) of syntactic error messages, which can

be overwhelming. Also, if we test only when we believe the program is finished,

we have no idea how to go about it. Finished programs are possibly
thousands

of lines long. There will be too much to test all at once, too many places that

might have errors. Programming, commenting, compiling, and testing incre-

mentally lends a great deal of control —and will your preserve sanity at 3am the

day your assignment is due.

Anglicizing integers

We write a function that anglicizes integers, producing their English equiv-

alents. For example, for the integer
2001
, our function produces the
String "two

thousand one"
. We start with a specification and a function heading:

/** =
English equivalent of
n
, for
0<n<1,000,000 */

public static
String anglicize(
int
n)

For small numbers like
2
and
5
, the English equivalent is easy to get; the

larger the number, the more work it takes to get its English equivalent. Because

of this we investigate large numbers, just to see what the problems are. The value

1000
is a point of differentiation: if
n ≥ 1000
the result has the word
"thousand"

in it; if
n < 1000
, it does not. Thus we can make an educated guess that the first

step of the body of anglicize is to make this differentiation:

/** =
English equivalent of
n
, for
0<n<1,000,000 */

public static
String anglicize(
int
n) {

if
(n >= 1000) {

return
anglicized
n (
for
1000 <= n < 1000000);

}
else
{

return
anglicized
n (
for
n <= 1000);

}

}

Refining the expression “anglicized n (for n > = 1000)”

Anglicizing an integer
n
in the range
1000 ≤ n < 1000000
requires breaking

it into the parts
n / 1000
and
n % 1000
, anglicizing the two parts, and placing
"

thousand "
between them. For example, the English equivalent of
2121
is the

word for
2121 / 1000
followed by
" thousand "
followed by the anglicization

of
2121 % 1000
. We can therefore write the then-part of the if-statement as

return
(
anglicized (
n/1000))

+ " thousand " + (
anglicized (
n % 1000))

This return statement calls for anglicizing two integers that are less than

1000
, and the else-part also calls for anglicizing an integer that is less than
1000
.

Therefore, in three places we have to do essentially the same task. It makes sense

Search WWH ::

Custom Search