Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    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);
    }
    }

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •