[英]Need assistance with java morse code translator only translating one symbol
[英]Need assistance with java morse code translator
我有一个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++)
应该是for (int m = 0; m < morse.length; m++)
所以您受到数字的限制字母中的字符数,而不是用户输入的字符数。 "inputMorseCode[m]"
。 将if (character.equals("inputMorseCode[m]"))
更改为if (character.equals(morse[m]))
首先,改变这个
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>
来将莫尔斯电码字符串映射为英文字符,反之亦然,您的代码将更加高效。 它们将替换您的摩尔斯和英语字母数组,并允许您在恒定时间内查找英语或摩尔斯字母的映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.