Hi,
I am getting an index out bound error for the following code.
Can anybody help me please? I have also attached the java source code file.
/**
* @(#)ReverseString.java
* Program to reverse a given string
*
* @author Marshall - Anzum.com- Hosting, SEO, Articles, Freelancing, E Learning, Downloads, How to, Online Jobs
* @version 1.00 2010/3/8
*/
//compiling well but giving index out of bound error
public class ReverseString {
static String reverse(String s)
{
int i,j=0;
char str[]=s.toCharArray();
System.out.println("Size of char array is"+str.length);
char []newstr={};
for(i=str.length;i>0;i--)
{
newstr[j]=str[i];
j++;
}
String r = new String(newstr);
return r;
}
public static void main(String args[])
{
String reversedString;
String sentence="Reverse Me";
reversedString=reverse(sentence);
System.out.println(reversedString);
}
}
Oops, all the four files appended. But we only need ReverseString.java
Thats because you initiate variable 'i' in the for loop with the length of s.
You should understand that if the length of an array is k, its indexes are 0,1,2,3,...k-1. The last index is always k-1 because you start counting from 0.
So instead of:
You should do something like:Code:for(i=str.length;i>0;i--)
note that the halting condition of the loop isCode:int lastIndex = str.length - 1; for (i = lastIndex; i>=0; i--) ...//rest of the code, because index 0 is still a legal index.Code:i>=0
Also the next code allocates array of length 0:
on the first write to this array you also will get OutOfBounds exception.Code:char []newstr={};
You should allocate an array of str.length characters:
Code:newstr = new char[str.length];
Thank you so much!
I can run the program successfully now![]()
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks