import java.util.*; public class stringReverse{ public static void main(String[]
ID: 3631767 • Letter: I
Question
import java.util.*;public class stringReverse{
public static void main(String[] args){
String input;
Scanner in = new Scanner(System.in);
System.out.print("Enter a string to reverse: ");
input = in.nextLine();
System.out.println(input + " reversed is: " + writeBackward (input));
}
public static String writeBackward (String s)
{
String ans = "", last, rest;
if (s.length() == 1)
return s;
else
{
last = s.substring(s.length() - 1, s.length());
rest = s.substring(0, s.length() - 1);
ans = last + writeBackward (rest);
return ans;
}
}
}
Adding comments to the code and explaining each section would be best. Thanks for the help!
Explanation / Answer
please rate: import java.util.*; public class stringReverse{ public static void main(String[] args){ String input; Scanner in = new Scanner(System.in); System.out.print("Enter a string to reverse: "); input = in.nextLine();//reading input string from user System.out.println(input + " reversed is: " + writeBackward (input));// calling function writeBackward } public static String writeBackward (String s) { String ans = "", last, rest; if (s.length() == 1)//s.length return the length of 's' input string return s; // if length=1 the same alphabet is returned as answer i.e reverse string else { last = s.substring(s.length() - 1, s.length());//finding the last letter of the input string rest = s.substring(0, s.length() - 1);//taking the remaining substring by removing the first //letter from the 's' input string ans = last + writeBackward (rest);//calling the writeBackward function recursively and //each time last letter become the first letter of new string named as ans return ans;// finally the reversed string is return by this function in main } } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.