String Reversal.... Not working
Code :
class jack
{
public static String reverseString(String s, String result,int l)
{
if(l>=0)
{ result=result+s.charAt(l);
reverseString(s,result,l-1);
return result;}
else
return "error";
}
public static void main(String args[])
{
String s="Allen downey";
String result="";
int l=s.length();
String backward=reverseString(s,result,l);
System.out.println(backward);
}
}
This program should reverse the string
But The program is not yielding output... I know what you are thinking.... why can't I just use while or for... But I can't... I am supposed to be able to write the program without any iteration...
please help...
Re: String Reversal.... Not working
Quote:
class jack
{
public static String reverseString(String s, String result,int l)
{
if(l>=0)
{ result=result+s.charAt(l);
reverseString(s,result,l-1);
return result;}
else
return "error";
}
public static void main(String args[])
{
String s="Allen downey";
String result="";
int l=s.length();
String backward=reverseString(s,result,l);
System.out.println(backward);
}
}
In the above code certain changes are required
Quote:
String backward=reverseString(s,result,l);
Firstly length you are passing should be one less than the actual length because you are directly using length as index value , but here index in a string or array starts from 0 .
Quote:
String backward=reverseString(s,result,l);
Code :
String backward=reverseString(s,result,l-1);
Secondly little modification in this part , while returning value
Quote:
if(l>=0)
{ result=result+s.charAt(l);
reverseString(s,result,l-1);
return result;}
else
return "error";
change required
Code :
if(l>=0)
{
result=result+s.charAt(l);
return reverseString(s,result,l-1);
}
else
return result;
Re: String Reversal.... Not working
OH MY GOD... u are a genius... Thank you so much... I have been trying to figure this out since yesterday... Thank you so very much....
thank you
thank you
Re: String Reversal.... Not working
Quote:
OH MY GOD... u are a genius... Thank you so much... I have been trying to figure this out since yesterday... Thank you so very much....
thank you
thank you
you r welcome , and please mark this thread as solved.