Question
Create an Eclipse project named Lab_Project_14, then create a class named Reverse with a main method. Then, complete the lab project: Recursion is an elegant,
Create an Eclipse project named Lab_Project_14, then create a class named Reverse with a main method.
Then, complete the lab project:
Recursion is an elegant, magical way to solve problems. The basic idea is to take a large problem and imagine how a solution to a smaller version of the problem could be used to solve the original problem.
Consider the problem of reversing the letters in a string. We will need a couple of String methods. Assume String s = "abcde".
s.charAt(0) returns the character "a".
s.substring(1) returns the string "bcde"
Lets plan a method for reversing the string that uses these methods. If the problem at hand is reversing s, we first need to think of a smaller related problem. Can you imagine one? Suppose we consider the problem of reversing the string bcde? Could the solution to this problem help us solve the original problem?
Here is a diagram of the solution:
One of the steps in the above process involves calling reverse("bcde"). The interesting thing about recursive methods is that you can solve the smaller problems by calling the method you are writing. Keep in mind you dont have to show how to solve all the smaller problems, you just have to show how a solution to a smaller problem can be used to solve the larger problem.
The process of shrinking the original problem cant continue forever, so we also have to specify the solutions to the smallest problems we encounter. In the example above, if the string s has a single character, we can simply return it as the solution (you can reverse a string with only one character). You can test for this by examining whether s.length() == 1. In a recursive solution, you have to test for the smallest cases first.
Implement a recursive method called reverse that is passed a String and that returns a String with the characters of the original string reversed. Use the following main code for testing your method.
public class Reverse { public static void main(String[] args) { String phrase = "abcdefg"; System.out.println("Original phrase: " + phrase ); System.out.println("Phrase reversed: " + reverse(phrase )); } // end main // Put your reverse method implementation here } // end Reverse
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started