我需要帮助将摩尔斯电码转换为英语。我已经编写并测试了将英语翻译成莫尔斯语的代码。我的主要问题是将莫尔斯电码中的所有字符放在一起,然后再将其翻译成英文字符(如果有意义的话)。
例子: ”。” 翻译成 E 和 ... 翻译成 S,但我不希望翻译在到达 ...
很少有规则-空格用于分隔莫尔斯字母-| 用作分隔单词的分隔符 - 不能使用哈希图 :(
这是我的代码
import java.util.Arrays;
import javax.swing.JOptionPane;
public class test3
{
public static void main ( String [] args )
{
String s1 = "Morse";
// Decide whether Morse code or English
String decide = JOptionPane.showInputDialog("Enter 'English' for Morse to English code translation and 'Morse' for English to Morse code translation. Pay attention to Caps.");
// Enter String & decide whether to convert to Morse or English
String phrase = JOptionPane.showInputDialog("Enter the words you wish to translate.");
if ( decide.equals( s1 ))
toMorse( phrase );
else
toEnglish( phrase );
}
// Translate to Morse
public static void toMorse( String preTranslation )
{
String[] 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"};
String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..", ".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--..",".----","..---","...--","....-",".....","-....","--...","---..","----.","-----"};
// Remove uppercase
String preTrans = preTranslation.toLowerCase();
// Deletes spaces
String phraseWithDelimiter = preTrans.replace( " ", "|");
String[] translation = new String[phraseWithDelimiter.length()];
String[] delimiter = {"|"};
// Translate
for ( int arrayVar = 0, transArrayVar = 0, subStringVarB = 0, subStringVarE = 1; transArrayVar < phraseWithDelimiter.length();)
{
if( phraseWithDelimiter.substring(subStringVarB, subStringVarE).equals( delimiter[0] ) )
{
translation[transArrayVar] = delimiter[0];
transArrayVar++;
subStringVarB++;
subStringVarE++;
}
else if ( phraseWithDelimiter.substring(subStringVarB, subStringVarE).equals( english[arrayVar] ) )
{
translation[transArrayVar] = morse[arrayVar];
transArrayVar++;
subStringVarB++;
subStringVarE++;
arrayVar = 0;
}
else
{
arrayVar++;
if ( arrayVar == 35 )
{
arrayVar = 0;
subStringVarB++;
subStringVarE++;
transArrayVar++;
}
}
}
String morseSeparator = new String( " " );
arrayToString ( translation, morseSeparator );
}
//Convert array to string and print translation
public static void arrayToString(String[] trans, String separator)
{
String result = "";
if (trans.length > 0)
{
result = trans[0]; // start with the first element
for (int i = 1; i < trans.length; i++)
result = result + separator + trans[i];
}
System.out.println( result );
}
// unfinished
public static void toEnglish( String preTranslation)
{
}
我正在考虑制作一个 for 语句并将摩尔斯电码的每个字符分配给一个新字符串,直到我到达一个空格,然后使用它进行测试,但我不确定如何做到这一点。
任何帮助表示感谢!