我有一个Java翻译器,当我从英语翻译到摩尔斯,而不是从摩尔斯翻译到英语。如果你能告诉我该怎么做才能翻译摩尔斯,那就太好了。当我从莫尔斯进入英语后,我输入我的莫尔斯代码,它只是结束程序,而不是给我翻译。
这是我的密码。
public class project1 {
public static void main ( String [] args ) {
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' };
String [] morse = { ".-" , "-..." , "-.-." , "-.." , "." , "..-." , "--." , "...." , ".." , ".---" , "-.-" , ".-.." , "--" , "-." , "---" , ".--." , "--.-" , ".-." , "..." , "-" , "..-" , "...-" , ".--" , "-..-" , "-.--" , "--.." , "|" };
String a = Input.getString ( "Please enter MC if you want to translate Morse Code into English, or Eng if you want to translate from English into Morse Code" );
if (a.equals("MC"))
{
String b = Input.getString ("Please enter a sentence in Morse Code. Separate each letter/digit with a single space and delimit multiple words with a | .");
String[] words = b.split("|");
for (String word: words )
{
String[] characters = word.split(" ");
for (String character: characters)
{
if (character.isEmpty()) { continue; }
for (int m = 0; m < b.length(); m++)
{
if (character.equals("inputMorseCode[m]"))
System.out.print(english[ m ]);
}
}
System.out.print(" ");
}
}
else if (a.equals("Eng"))
{
String c = Input.getString ( "Please enter a sentence in English, and separate each word with a blank space." );
c = c.toLowerCase ();
for ( int x = 0; x < english.length; x++ )
{
for ( int y = 0; y < c.length (); y++ )
{
if ( english [ x ] == c.charAt ( y ) )
System.out.print ( morse [ x ] + " " );
}
}
}
else
{
System.out.println ( "Invalid Input" );
}
}
}发布于 2015-05-30 18:42:28
首先,改变这个
for (int m = 0; m < b.length(); m++)
{
if (character.equals("inputMorseCode[m]"))
System.out.print(english[ m ]);
} 至
for (int m = 0; m < morse.length; m++)
{
if (character.equals(morse[m]))
System.out.print(english[m]);
} 因为你应该在摩尔斯数组中搜索摩尔斯字母。
尽管如此,如果您创建一个将morse映射到英文字符的Map<String,Character>和Map<Character,String>,那么您的代码将更加高效,反之亦然。它们将替换您的morse和english数组,并允许您在恒定时间内找到英文或莫尔斯字母的映射。
发布于 2015-05-30 18:42:15
for (int m = 0; m < b.length(); m++)应该是for (int m = 0; m < morse.length; m++),因此您受到字母表中字符数的限制,而不是用户输入的字符数。"inputMorseCode[m]"进行比较。将if (character.equals("inputMorseCode[m]"))更改为if (character.equals(morse[m]))https://stackoverflow.com/questions/30549859
复制相似问题