Using java write a computer program that uses a recursive algorithm to reverse s
ID: 3584989 • Letter: U
Question
Using java
write a computer program that uses a recursive algorithm to reverse strings until the user types “done” as the entry string.
Read in a string from the user. Prompt her with something like “Enter the string to reverse, or ‘done’ to exit. If the user enters “done” then exit.
Use a recursive algorithm and implementation to reverse the string.
The program should loop through these two steps until the user indicates they are done. For example, if the user entered “Finally” the program would reverse the string so that it was “yllaniF” and would display that. Then it would prompt for the next string.
Hints:
View the string as String or an array of characters, depending on the language you are using, and your preferences. You can use the recursion to move one character of the array from the beginning to the end. Then you can call the method/function recursively to reverse the rest of the string.
What if the string is of even length? What if it is odd? What do you need to do to handle those cases (if anything)?
Explanation / Answer
ReverseStringRecursive.java
import java.util.Scanner;
public class ReverseStringRecursive {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string to reverse, or ‘done’ to exit: ");
String s = scan.next();
while(!s.equalsIgnoreCase("done")) {
System.out.println("Reverse String: "+reverseString(s));
System.out.println("Enter the string to reverse, or ‘done’ to exit: ");
s = scan.next();
}
}
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, or ‘done’ to exit:
Finally
Reverse String: yllaniF
Enter the string to reverse, or ‘done’ to exit:
abcde
Reverse String: edcba
Enter the string to reverse, or ‘done’ to exit:
done
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.