Java Reference

In-Depth Information

Javanize and prepend
. We coined the word
javanize
to mean “refine into Java”, or “replace by

an equivalent Java statement or expression”.

To
append
a value to a list means to insert it at the end of the list. There

exists no corresponding word to add the value at the beginning of the list, so we

have coined one. To
prepend
a value to a list means to insert it at the beginning

of the list.

15.1.3

A recursive function

We develop a function to return its
String
parameter but with blanks removed:

Activity

15-1.3

/** = p
, with blank characters removed
*/

public static
String deblank(String p)

For example, if the argument is the string
" a b c "
, the result of the call is the

string
"abc"
:

deblank(" a b c ")
is
"abc"

If the argument contains only blank characters (or no characters at all), the

result of the call is the empty
String
:

See lesson

page 15.1 to

get the function

from the CD.

deblank(" ")
is
""

In writing the method body, there are two cases to consider. The base case is

the case that
p
is the empty
String
; there are no blanks to remove, and
p
itself

can be returned.

The case that
p
contains at least one character itself breaks into two cases.

(1) If the first character of
p
is a blank, the result is the rest of
p
but with blanks

removed. (2) If the first character is not a blank, the result is the first character

prepended to (the rest of
p
but with blanks removed). This yields this body, with

some parts still in English:

if
(p.length() == 0) {

return
p;

}

// { p
has at least one character
}

if
(p.charAt(0) == ' ')

{
r
eturn
p[1..]
but with blanks removed
; }

// {
first character of
p
is not a blank
}

return
p.charAt(0)
+
(p[1..]
, but with blanks removed
);

This function is correct, but it has two English expressions, which we have

to Javanize. The expression (
p[1..]
but with blanks removed) is the same as the

value of the function given in the specification, except that the expression has

p[1..]
instead of parameter
p
. Therefore, the expression can be implemented

using the Java expression

Search WWH ::

Custom Search