2. Consider that we can define the reverse of a string s recursively as: reverse
ID: 3589174 • Letter: 2
Question
2. Consider that we can define the reverse of a string s recursively as: reverse (s) = s if s.equals("") (an empty string is its own reverse) reverse (s) = s.charAt(s.length() - 1) + reverse(s.substring(0, s.length() - 1)) a) Create an application that prompts the user for a string, then outputs the string in reverse. For example, if the user inputs "abcd efg," then your application should output "gfe dcba." Within your application include a static recursive method reverse based on the above definition, that takes a String argument and returns a String that is the reverse of the argument. b) Show the sequence of method calls to reverse that your application makes if the user inputs "RECURSE."
Explanation / Answer
ReverseString.java
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string to reverse: ");
String s = scan.nextLine();
System.out.println("Reverse String: "+reverseString(s));
}
public static String reverseString(String s) {
if(s.length() == 1) {
return s;
} else {
return s.charAt(s.length()-1)+reverseString(s.substring(0,s.length()-1));
}
}
}
Output:
Enter the string to reverse:
abcd efg
Reverse String: gfe dcba
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.