Question: Modify the previous exercises Recurse program so that it uses tail recursion. Minimize code changes. You should be able to do this with exactly the
Modify the previous exercise’s Recurse program so that it uses tail recursion. Minimize code changes. You should be able to do this with exactly the same number and sequence of statements and with only internal alterations to one line in the main method and three lines in the recurse method.
Exercise 11.3
Many times, you have used Scanner methods to read and parse keyboard input. You can also use those same Scanner methods to read and parse an ordinary string. The following program uses the Scanner class’s now-familiar next method, but this time it reads from a string instead of the keyboard. When the next method executes, there’s an internal cursor that remembers how much of the string has been processed so far and how much has yet to be processed. The program uses the Scanner class’s hasNext method to check whether there is any more of the string that has yet to be processed. Study the code. What does the program display for output? Note the recursive return statement that says “// explain.” Explain how that statement works.

import java.util.Scanner; public class Recurse { public static String recurse (Scanner scan) { String item = ""; if (scan.hasNext()) { item = scan.next() + } if (item.equals("")) ( } else ( return item; if (scan.hasNext()) { scan.next(); } return item + recurse (scan); // explain } } // end recurse 11 //****** public static void main(string[] args) { String string = "Jack and Jill went up the hill" + " to fetch a pail of water"; Scanner scan new Scanner (string); string= recurse (scan); System.out.println(string); 3 // end main } // end Recurse
Step by Step Solution
3.38 Rating (173 Votes )
There are 3 Steps involved in it
The given program uses recursion to read and process a string token by token The recurse method uses ... View full answer
Get step-by-step solutions from verified subject matter experts
