CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   Need help with ArrayIndexOutOfBoundsException (http://www.codingforums.com/showthread.php?t=266782)

SeventhSandwich 07-01-2012 02:06 AM

Need help with ArrayIndexOutOfBoundsException
 
I'm just learning java and I thought I would try my hand at making a program that would print a string backwards. So what I tried to do was write out the text from the string in a character array and then fill another character array from end to beginning. Problem is I keep getting an ArrayIndexOutOfBoundsException error every time. I'm not sure what's wrong considering I tested the length of stringholder1 and it was 22, so I don't see why I'm getting the error.

Here's the code:
Code:

package classtest;


public class Classtest {

    public static void main(String[] args) {
        String s = "This will be backwards";
        char stringholder1[];
        char stringholder2[] = new char[22];
        int b;
        stringholder1 = s.toCharArray();
        for(int i=1;i<23;i++) {
            stringholder2[i] = stringholder1[22-i];
        }
        String s2 = new String(stringholder2);
        System.out.println(s2);
}
}


Fou-Lu 07-01-2012 04:49 PM

Code:

for(int i=1;i<23;i++) {
            stringholder2[i] = stringholder1[22-i];
        }

This sets i to one for the first iteration. Doing so places the first (that is, the last character of the original string) into the second location of the stringholder2.

Avoid the magic numbers. I'd use two variables for the loop control only because I think it looks cleaner (ikr I've gotta be weird for that :P):
Code:

        for (int i = 0, j = stringholder1.length - 1; j >= 0; ++i, --j)
        {
                stringholder2[i] = stringholder1[j];
        }

I'd recommend initializing stringholder2 after that of stringholder1 since you can make it sized to stringholder2.length - 1.


All times are GMT +1. The time now is 12:55 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.