我正在尝试创建一个 gui 应用程序,它可以读取英语用户输入并转换为 morse(http://ascii-table.com/morse-code.php)。到目前为止,我已经触及了程序的基本部分。我的问题是;阅读莫尔斯的最佳方法是什么?我应该创建一个文本文件来导入莫尔斯字母,还是应该在程序中声明它们中的每一个来翻译?下一个问题是我将如何去做?如果可能,请参考教程。谢谢你的时间。
问问题
411 次
3 回答
2
由于摩尔斯电码不太可能改变,硬编码字符到代码字符串的映射是一个有效的选择:
private static Map<Character,String> charToCode = new HashMap<Character,String>();
{
charToCode.put('A', ".-");
charToCode.put('B', "-...");
...
charToCode.put('Z', "--..");
}
此映射允许您一次将消息转换为代码一个字符:
StringBuilder
为结果做一个- 一次遍历输入的字符。你可以使用
charAt(i)
它 - 将字符转换为大写
- 用于
charToCode.get(upperChar)
查找字符的代码表示 - 将表示附加到
StringBuilder
; 在它后面附加一个空格 - 循环结束后,转换
StringBuilder
为String
,并将其放在标签上。
于 2015-05-16T13:32:57.877 回答
1
您可以在外部维护两个文件。一个具有从字母到摩尔斯电码的映射,另一个具有从摩尔斯电码到字母的映射。然后,您可以通过从相应文件中查找来构建这两个转换器。
于 2015-05-16T13:24:39.687 回答
0
您可以读取用户的输入并在运行时将它们与程序中存储的预定义字符和数字进行比较,或者您可以输入文件并使用 FileReader 读取它
但这是您应该为运行时间比较执行的逻辑
char[] english = { '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', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
',', '.', '?' }; //Defining a Character Array of the English Letters numbers and Symbols so that we can compare and convert later
String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
"-----", "--..--", ".-.-.-", "..--.." };
System.out.println("-->Enter the Sentence that you want to Transmit Using the Morse Code ");
System.out.print("->");
sentence = br.readLine();
System.out.println("");
sentence = sentence.toLowerCase(); //Because morse code is defined only for the lower case letters and the numbers and the Symbols will remain the Same
char[] morsec = sentence.toCharArray();
for(int i = 0; i < morsec.length;i++) //The loop will run till i is less than the number of characters in the Sentence because Every Character needs to Be Converted into the Respective Morse Code
{//For Every Letter in the User Input Sentence
for(int j = 0;j<english.length;j++) //For Every Character in the morsec array we will have to traverse the entire English Array and find the match so that it can be represented
{
if(english[j] == morsec[i]) //If the Character Present in English array is equal to the character present in the Morsec array then Only Execute
{//Always remember that the condition in the Inner loop will be the first to be Equated in the If Statement because that will change until the characters match
answer = answer + morse[j] + " "; //After Every Letter is generated in the Morse Code we will give a Space
} //Since the Letters in the English char and the symbols present in the morse array are at the Same Index
}
}
System.out.println("-->The Morse Code Translation is:- ");
System.out.Println(answer);
于 2017-06-30T10:17:29.173 回答