This is a method I wrote using recursion to reverse a string. Recursions really not the best solution for anything, but this one turned out pretty cool.
Code:
public class ReverseString
{
public String reverse(String arg)
{
String tmp = null;
if (arg.length() == 1)
{
return arg;
}
else
{
String lastChar = arg.substring(arg.length()-1,arg.length());
String remainingString = arg.substring(0, arg.length() -1);
tmp = lastChar + reverse(remainingString);
return tmp;
}
}
}
Code:
import java.io.*;
public class TestReverse
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter a line to be reversed");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inData;
inData = br.readLine();
ReverseString rs = new ReverseString();
System.out.println("Reversed: " + rs.reverse(inData));
}
}