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 “$$”.
Code Java:
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!
Re: Why isn't this 2D array working?
i think the problem with print(test) method. Please post the print(String[][]) method.
Re: Why isn't this 2D array working?
Quote:
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.