Java Reference
In-Depth Information
Additional review exercises are available in WileyPLUS.
618
619
PROGRAMMING EXERCISES
΢ Exercise P13.1. Write a recursive method void reverse() that
reverses a sentence. For example:
Sentence greeting = new Sentence("Hello!");
greeting.reverse();
System.out.println(greeting.getText());
prints the string "!olleH" . Implement a recursive solution by removing
the first character, reversing a sentence consisting of the remaining text,
and combining the two.
΢΢ Exercise P13.2. Redo Exercise P13.1 with a recursive helper method that
reverses a substring of the message text.
΢ Exercise P13.3. Implement the reverse method of Exercise P13.1 as an
iteration.
΢΢ Exercise P13.4. Use recursion to implement a method boolean
find(String t) that tests whether a string is contained in a sentence:
Sentence s = new Sentence("Mississippi!");
boolean b = s.find("sip"); // Returns true
Hint: If the text starts with the string you want to match, then you are done.
If not, consider the sentence that you obtain by removing the first character.
΢΢ Exercise P13.5. Use recursion to implement a method int
indexOf(String t) that returns the starting position of the first
substring of the text that matches t . Return ɨ1 if t is not a substring of s .
For example,
Sentence s = new Sentence("Mississippi!");
int n = s.indexOf ("sip"); // Returns 6
Search WWH ::




Custom Search