For homework I am trying to print all possible combinations of letters that can be represented using the numeric keypad on a telephone. This problem is the same as the one posted here: How can I print out all possible letter combinations a given phone number can represent?
I keep getting a String index out of range: 0 problem but I'm not 100% sure why. Here is the code:
public class TelephoneKeyPad2 {
public static String keyPad[][] = {
{"0"}, {"1"}, {"A", "B", "C"}, {"D", "E", "F"}, {"G", "H", "I"},
{"J", "K", "L"}, {"M", "N", "O"}, {"P", "Q", "R", "S"},
{"T", "U", "V"}, {"W", "X", "Y", "Z"}
};
public static void tpK(String num, StringBuilder combination) {
if (num.length() == 0) {
System.out.println(combination);
}
for (String letter: keyPad[Character.getNumericValue(num.charAt(0))]) {
tpK(num.substring(1), combination.append(letter));
}
}
public static void main(String[] args) {
tpK("345", new StringBuilder());
} }
I have a feeling it's because of the if statement...there is no way to break the recursion after num.length == 0 is confirmed to be true, so the string index out of range. I am not sure how to fix this problem and any help would be appreciated.
EDIT: So it seems like it may be just a logic problem then afterwards.
DGJ
DGJK
DGJKL
DGJKLHJ
DGJKLHJK
are example outputs so now I'm really confused on how to solve this problem as well.