我有一个 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" );
}
}
}
最佳答案
首先,改变这个
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]);
}
因为您应该在莫尔斯数组中搜索莫尔斯字母。
也就是说,如果您创建 Map<String,Character>
,您的代码将会更加高效。和Map<Character,String>
将莫尔斯字符串映射到英文字符,反之亦然。它们将取代您的莫尔斯电码和英语数组,并允许您在恒定时间内找到英语或莫尔斯电码字母的映射。
关于java - 需要 java 摩尔斯电码翻译器的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30549859/