# Inserting characters from string into 2d array?

• April 12th, 2013, 04:40 AM
amf19
Inserting characters from string into 2d array?
Hi there,
I am new to java and am having trouble with some code... I am trying to input the characters from a string into a 2d array. The array size depends on the amount of characters in the string (get the square root and round up to the nearest int so that the array is a square grid). I'm getting an out of bounds error, but not sure why. I would appreciate any help! Thanks :)

This is what I have so far:

Code java:

```public class Practice { public static void main(String[] args) {   String text = args[0]; text = text.replaceAll("\\s", ""); text = text.toLowerCase(); System.out.println(text);   float squareRoot = (float) Math.sqrt(text.length()); int dimension = (int) Math.ceil(squareRoot); int x = dimension; int y = dimension;   char[] charArray = text.toCharArray(); char[][] myArray = new char[x][y]; int nextChar = 0; for (int a = 0; a < x; ++a) { for (int b = 0; b <y; ++b) { myArray[x][y] = charArray[nextChar]; nextChar++; } } } }```
• April 12th, 2013, 04:50 AM
PhHein
Re: Inserting characters from string into 2d array?
You're iterating x*y times, which is likely more than charArray.length, because you round up. So nextchar will be >= than charArray.length, causing the Exception.
• April 12th, 2013, 04:59 AM
amf19
Re: Inserting characters from string into 2d array?
ah, thank you.. that makes sense. Still unsure as to how I would go about fixing this though?
• April 12th, 2013, 05:05 AM
PhHein
Re: Inserting characters from string into 2d array?
You have to stop looping as soon as nextchar will be >= charArray.length
• April 12th, 2013, 05:18 AM
amf19
Re: Inserting characters from string into 2d array?
I've tried putting an if statement in, but that doesn't seem to work:

Code java:

``` char[] charArray = text.toCharArray(); char[][] myArray = new char[x][y]; int nextChar = 0; for (int a = 0; a < x; ++a) { for (int b = 0; b < y; ++b) { if (nextChar < charArray.length) { myArray[x][y] = charArray[nextChar]; nextChar++; } } }```
• April 12th, 2013, 05:40 AM
PhHein
Re: Inserting characters from string into 2d array?
What does "doesn't seem to work" mean? Did you blow up your toaster? What error messages/stack traces do you get now?
• April 12th, 2013, 05:45 AM
amf19
Re: Inserting characters from string into 2d array?
I still get the same error - out of bounds exception
• April 12th, 2013, 05:51 AM
PhHein
Re: Inserting characters from string into 2d array?
Aha! You're not using the loop variables as index!
Code :

`myArray[a][b] = charArray[nextChar];`
You're using x and y which are out of bounds.
• April 12th, 2013, 06:01 AM
amf19
Re: Inserting characters from string into 2d array?
You're right! Still out of bounds error though after fixing!!

--- Update ---

Wait ignore last post, it worked! Thank you so much