Require Help with Decoder Program
EDIT: Nevermind, I fixed it. I changed the decryption to a String array instead of an int array and I cast the (65 + index) as a char...
So I have a homework problem for a class, which entails decoding a long string of binary numbers. To decode the message I had to change the letters of the alphabet and spaces into a Huffman code based off of letter frequencies in the english language. Luckily, I have already done this and I believe I have the decryption correct; however, I do not want to have to go through the code by hand and decode it, so I thought I would write a program to do it. I have written the following:
*Sorry, not sure how to post with correct formatting
public class ECE_Decoder {
public static void main(String[] args) {
String code = "101010101...(This isn't correct, but just imagine a long string of seemingly random binary numbers)";
String subCode = "";
int[] decryption = { 1010, 110010,... 100 (Again not correct, but basically I have an array with slot 0 representing the code for 'A', slot 1 for 'B', etc. to slot 26 for " " (or a space, in other words) )};
for (int i = 0; i < code.length(); i++) {
subCode += code.charAt(i); //I'm assuming this is the main problem, but I don't know why it might be wrong
System.out.println(subCode); //used for debug purposes only
for (int index = 0; index < decryption.length; index++) {
if (Integer.parseInt(subCode) == decryption[index]) {
if (index == 26) {
System.out.print(" ");
} else {
System.out.print(65 + index);
}
subCode = "";
break;
} else {
continue;
}
}
}
}
}
So if you didn't know, Huffman codes are great because they are completely unique for each object encoded. This means that if A = 1001, no other code will start with 1001. Because of this, I wanted the program to just go through checking a subsection of the string against the Huffman codes I have in the decryption array. First checking if the first char fits any of the codes, if it does it should print the correct letter or space it represents; if it doesn't it should add the next char to the string and check again, and so on. However, when I run the code nothing prints. I added the System.out.println(subCode) after to see what the problem might be and I got this list:
1
691
690
801
691
691
690
800
801
690
800
801
690
801
...
The first print seems to be correct, but then after that it goes off the rails. I'm thinking I either have a typo somewhere or there is some fundamental thing about java (in Strings or whatever) that I am unaware of. I just need a more experienced set of eyes to look at it and help me fix it if possible. Thanks in advance.