Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Members have full access to the forums. Advertisements are removed for registered users.

# Thread: Why isn't this 2D array working?

1. ## Why isn't this 2D array working?

Given a 2D array of Strings and a non-empty array of Strings where each string is of length 2 or more. Write a method that will place the first 2 chars of each String into a 2D array in row major order. If the 1D array runs out of strings then fill in the rest of the elements with “\$\$”.

```
public static void main(String[] args)
{

String[][] t = new String[2][3];
String[][] test;
String[] words = {"hello", "blah", "boom", "elephant"};
test = twoCharsTo2D(t, words);
print(test);

}

public static String[][] twoCharsTo2D(String[][] table, String[] words)
{
for(int r = 0; r<table.length; r++)
{
for(int c = 0; c<table[r].length; c++)
{
table[r][c] = "\$\$";
}
}
int counter = 0;
for(int rows = 0; rows<table.length; rows++)
{
if(counter==words.length)
break;
for(int col = 0; col<table[rows].length; col++)
{

table[rows][col] = words[col].substring(0,3);
counter++;
}
}
return table;

}```

It's a simple problem, but when I try printing this method I get

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

Thanks!

2. ## Re: Why isn't this 2D array working?

i think the problem with print(test) method. Please post the print(String[][]) method.

3. ## Re: Why isn't this 2D array working?

ava.lang.ArrayIndexOutOfBoundsException: 2
Please post the full text of the error message that shows where the error happens.
The error says that there is an index past the end of the array.
Remember that the indexes for an array range from 0 to the length-1
The max index for an array with 2 slots is 1.