我正在开发一个可以将莫尔斯电码翻译成英语的项目,反之亦然。具体说明如下:“你的程序应提示用户指定所需的翻译类型,输入一串摩尔斯电码字符或英文字符,然后显示翻译结果。 输入摩尔斯电码时,每个字母/数字之间用一个空格分隔,多个单词之间用“|”分隔。例如,- --- | -....将是句子“to be”的摩尔斯电码输入。你的程序只需要处理一个句子,可以忽略标点符号。”
虽然我知道如何将英语翻译成莫尔斯电码,但我不知道如何将莫尔斯电码翻译成英语。如果您正在阅读本文,请帮助我!任何帮助或提示将非常感激!谢谢:)
public static String[] morse = { ".- ", "-... ", "-.-. ", "-.. ", ". ",
"..-. ", "--. ", ".... ", ".. ",
".--- ", "-.- ", ".-.. ", "-- ", "-. ", "--- ", ".--. ", "--.- ",
".-. ", "... ", "- ", "..- ",
"...- ", ".-- ", "-..- ", "-.-- ", "--.. ", "|" };
public static String[] alphabet = { "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 main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input '1' to translate English to Morse Code.");
System.out.println("Input '2' to translate Morse Code to English.");
int kind = in.nextInt();
if (kind == 1) {
System.out.println("Please insert an alphabet string");
String Eng = in.next();
EngToMo(Eng);
}
if (kind == 2) {
System.out.println("Please insert a morse string");
String Mor = in.next();
MoToEng(Mor);
}
}
public static void EngToMo(String string1) {
String Upper1 = string1.toUpperCase();
for (int i = 0; i < Upper1.length(); i++) {
char x = Upper1.charAt(i);
if (x != ' ') {
System.out.print(morse[x - 'A'] + " ");
} else {
System.out.println(" | ");
}
}
}
public static void MoToEng(String string2) {
}
}
最佳答案
我建议使用Hashtable创建一个字典,其中字母可以用作Key,相关的摩尔斯电码可以与此Key配对。如果您想拥有唯一的键值对,您可以使用 BiMap用于存储。
Map<String, String> codeMap = new HashMap<String, String>();
codeMap.put("A", ".- ");
codeMap.put("B", "-... ");
您可以轻松访问此 map 以获取键或值
for (String key: codeMap.keySet() ){
System.out.println(key+" : "+codeMap.get(key) );
}
关于java - 将摩尔斯电码翻译成字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28018666/