Write a java program (name it ReverseString) as follows: The main method prompts
ID: 3718695 • Letter: W
Question
Write a java program (name it ReverseString) as follows:
The main method prompts the user to enter a string. The method then calls Method Revers()(defined blew) to recursively reverse and display the entered string. Method Revers()is of type void, it takes a string parameter and recursively print out the string in reverse order.
Document your code and use proper prompts for input and format outputs as shown below.
Entered string: This is a test
Reversed string: tset a si siht
Entered string: Hello world
Reversed string: dlrow olleH
Explanation / Answer
import java.util.Scanner;
public class ReverseString {
private int idx;
private String text, revText;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string :");
String input=sc.nextLine();
ReverseString greeting = new ReverseString(input);
System.out.println(" Enterd String :"+input);
greeting.Revers(input);
System.out.println("Reversed String :"+greeting.getText());
}
public void Revers(String input) {
if (idx == text.length())
return;
revText = text.charAt(idx) + revText;
idx++;
Revers(input);
}
public ReverseString(String _text) {
idx = 0;
text = _text;
revText = "";
}
public String getText() {
return revText;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.