Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-01-2012, 02:06 AM   PM User | #1
SeventhSandwich
New to the CF scene

 
Join Date: Jul 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
SeventhSandwich is an unknown quantity at this point
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);
}
}
SeventhSandwich is offline   Reply With Quote
Old 07-01-2012, 04:49 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,650
Thanks: 4
Thanked 2,451 Times in 2,420 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
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.
Fou-Lu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:32 AM.


Advertisement
Log in to turn off these ads.