我的代码在将常规文本编码为摩尔斯电码时效果很好,但是当我尝试以另一种方式翻译时,我遇到了索引越界错误。不知道为什么?
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;
}
}
试图找到一个双向工作的解决方案,任何帮助/建议将不胜感激!