我有一个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" );
}
}
}
答案 0 :(得分:0)
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]))
答案 1 :(得分:0)
首先,改变这个
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>
,那么你的代码效率要高得多,那就是将莫尔斯字符串映射到英文字符,反之亦然。他们会替换你的莫尔斯和英语数组,并允许你在不变的时间内找到英文或莫尔斯字母的映射。