My code works fine on encoding regular text to Morse code, but when i attempt to translate the other way, I am hit with an index out of bounds error. No idea why?
import java.util.HashMap;
public class MorseCode {
private final String alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 ";
private final String[] morse = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",
".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....",
"-....", "--...", "---..", "----.", "-----", "|"};
private HashMap<String, String> toText;
private HashMap<String, String> toCode;
public MorseCode() {
toText = new HashMap<>();
toCode = new HashMap<>();
char[] alphaArray = alphabet.toCharArray();
for(int i = 0; i < morse.length; i++) {
toCode.put(morse[i], String.valueOf(alphaArray[i]));
toText.put(String.valueOf(alphaArray[i]), morse[i]);
}
}
public String encode(String s) {
s = s.toLowerCase();
String encoded = "";
char[] chars = s.toCharArray();
for(int i = 0; i < s.length(); i++) {
for (HashMap.Entry<String, String> entry : toCode.entrySet()) {
if (String.valueOf(chars[i]).equals(entry.getValue())) {
encoded += entry.getKey() + " ";
}
}
}
return encoded;
}
public String decode(String s) {
s = s.toLowerCase();
String decoded = "";
for(int i = 0; i < s.length(); i++) {
for (HashMap.Entry<String, String> entry : toText.entrySet()) {
if (morse[i].equals(entry.getValue())) {
decoded += entry.getKey();
}
}
}
return decoded;
}
}
Trying to find a solution that works both ways, any help/advice would be appreciated!
I tested this code and it is working. Be aware that this is a very rudimentary implementation, but properly using some of the conveniences of the HashMap class. I strongly advise you running in debug mode and tracing the values of the variables.
Test code in the main method. This test should really take all boundary cases (special characters, multiple spaces, empty strings, etc) and compare the input with the expected output. But it's too late for that. :-)
Cheers.