JAVA Assignment Description: (Using The Module One Readings) In this program you
ID: 3586098 • Letter: J
Question
JAVA Assignment
Description: (Using The Module One Readings) In this program you will design and write a computer program to execute the following task. Basically, it 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. 1. 2. 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 yoiu 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
import java.io.*;
import java.util.*;
public class DemoRev{
public static String reverse(String str){
String rev = "";
if (str.length() == 1){
return str;
}
else {
return rev + str.charAt(str.length()-1) + reverse(str.substring(0,str.length()-1));
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = "abc";
while (true){
System.out.println("Enter a string to reverse or done to exit:");
String line = sc.nextLine();
if (line.equals("done"))
break;
System.out.println(reverse(line));
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.