VigilanteCS
Senior member
Hi, I'm having trouble with an assignment to reverse a string using recursion ( ex. "green" , "neerg". All I can figure out how to do is have it output the last letter first, nothing else. I'll show you the code from the recursion method down.
public static String reverse(String n)
{
if(n.length() == 1)
{
return n + " ";
}
else
{
//this is where I'm having trouble
return n.substring(n.length() -1, n.length());
}
public static void main(String[] args)
{
recursion recursion = new recursion()'
String x = reverse("green");
JOptionPane.showMessageDialog(null, x);
System.exit(0);
}
When I write reverse in front of n.substring (which I know I'm supposed to do)I get a fatal exception error, without it it outputs "n". I know I'm supposed to have reverse in front of the return statement in the else. I know that the actual code in the else section isn't correct as well. Any help would be greatly appreciated! Thanks!
public static String reverse(String n)
{
if(n.length() == 1)
{
return n + " ";
}
else
{
//this is where I'm having trouble
return n.substring(n.length() -1, n.length());
}
public static void main(String[] args)
{
recursion recursion = new recursion()'
String x = reverse("green");
JOptionPane.showMessageDialog(null, x);
System.exit(0);
}
When I write reverse in front of n.substring (which I know I'm supposed to do)I get a fatal exception error, without it it outputs "n". I know I'm supposed to have reverse in front of the return statement in the else. I know that the actual code in the else section isn't correct as well. Any help would be greatly appreciated! Thanks!