2. Consider that we can define the reverse of a string s recursively as: reverse
ID: 3791585 • 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
The Java code where the string can be reveresed would be as under.
import java.util.*;
class ReverseString // declaring the class a Reverse String
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");// Asking the user to enter the text
original = in.nextLine();
int length = original.length();// Program capturing the origincal length of the string
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);// output of the string
}
}
____________________________________________________________________________________
The sequence of method if the user inputs recursive
import java.util.Scanner;
class RecursionReverseDemo // declaring the class of RecursionReverseDemo
{
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
//Method is calling itself: recursion
reverseMethod(number/10);
}
}
public static void main(String args[])
{
int num=0; System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
System.out.print("Reverse of the input number is:");
reverseMethod(num);
System.out.println();//would print the recursive number
}
}
The above code would ask the user to enter the code and would return unlike wise as recursive.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.