Java Reference
In-Depth Information
all of which are short and almost trivial. It could be called a functional approach ,
since there are no assignments and all the work is done using function calls (and
the if- and return statements). It is an effective manner of programming, and
entire programming languages (e.g. LISP and Scheme) have been built on it.
It is possible to use a procedural approach to solve this problem, ending up
with a program that has fewer functions and whose main function contains some
local variables that are being manipulated. We outline this approach here.
To set the stage, consider the following. When summing a list of values, we
would initialize a variable x (say) to 0 and then, one by one, add values to x .
In the problem of anglicizing n , we can imagine initializing a String vari-
able s to be the empty string "" and then, little by little, appending pieces of the
English equivalent to s . In doing this, we let an integer variable k tell us what
remains to be anglicized and appended to s .
Thus, we start out with this function:
Activity 2-5.4.
The activity
gives the com-
plete develop-
ment, in a way
that is impossi-
ble on paper.
/** = English equivalent of n , for 0<n<1,000,000 */
public static String anglicize( int n) {
// anglicize(n) = s + ( the English equivalent of k)
int k= n; // the part of n left to translate
String s= ""; // the translation so far
Reduce k to 0 , keeping the definition of s and k true ;
return s;
}
We cannot overemphasize the importance of the definition of s and k as:
anglicize(n) = s + ( the English equivalent of k)
In developing the method body, this definition will be the key. Note, for
example, how the statement before the return statement refers to this definition.
Assuming that the English equivalent of 0 is "" , this is a correct description of
the task. We can refine the statement to reduce k to 0 as follows. The first step,
as it was in the functional approach, is to deal with the case when k ≥ 1000 . We
refine anglicize to deal with this case:
/** = English equivalent of n , for 0<n<1,000,000 */
public static String anglicize( int n) {
// anglicize(n) = s + ( the English equivalent of k)
int k= n; // the part of n left to translate
String s= ""; // the translation so far
// Handle the part that is ≥ 1000
if (k >= 1000) {
s= s + ( English equivalent of k / 1000) + " thousand ";
k= k % 1000;
}
Search WWH ::




Custom Search