【发布时间】:2020-11-28 18:38:17
【问题描述】:
所以我制作了一个运行良好的摩尔斯电码解码器。唯一的问题是它不能补偿条目开头和结尾的空白。所以说我有“。”这是摩尔斯电码中的E。我应该能够输入“__._”并得到相同的结果,但我只是得到了一个例外。当它进入时,我尝试在条目上使用修剪方法,这消除了异常,但我没有得到任何输出。我尝试使用循环来摆脱前面的空白,但我没有得到任何输出,即使这样有效,我仍然需要弄清楚如何处理后面的空白。这是我的代码:
static 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",
",", ".", "?","!","@","&","(",")"}; //Defining a Character Array of the English Letters numbers and Symbols so that we can compare and convert later
static String[] morse = { " " ,".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
"-----", "--..--", ".-.-.-", "..--..","-.-.--",".--.-.",".-...","-.--.","-.--.-"};
public static String Decode (String morseCode)
{
String MLetter= "";//Morsec array to hold individual characters
String ELetter ="";//English Letter String
morseCode+=" ";
for(int i=0; i<morseCode.length();i++)//put characters into the morse String
{
if(morseCode.substring(i,i+1).equals(" "))//if a space is detected
{
for(int j=0; j<morse.length;j++)// then compare the string to the morse array
{
if(MLetter.equals(morse[j]))//if the morse string equals the morse index
{
ELetter+=english[j];//add the english equivilent
MLetter="";//and clear the Morse string
i++;//Skip the space
}
}
}
MLetter+= morseCode.substring(i,i+1);//add the character to the Morse String
}
return ELetter.toUpperCase();
}
【问题讨论】:
标签: java loops whitespace removing-whitespace morse-code