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!