我已经看到很多关于莫尔斯电码翻译器的问题,并查看了其中的许多问题,但在所有这些问题中,建议的答案都给了我相同的错误输出。代码背后的想法是能够使用数组将摩尔斯电码翻译成英语,反之亦然。我的代码如下:
import java.util.Scanner;
public static void main ( String [] args )
{
String [] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "|"};
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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", " "};
Scanner input = new Scanner ( System. in );
System.out.println ( "Enter 1 to translate Morse Code to English or 2 to translate English to Morse Code:");
int userChoice = input.nextInt();
String translateMe;
while (userChoice < 1 || userChoice > 2 ) // Ensures user enters a valid choice
{
System.out.println( "Not a valid entry. Enter 1 to translate Morse Code to English or 2 to translate English to Morse Code:");
userChoice = input.nextInt();
}
if (userChoice == 1 )
{
System.out.println("Please enter a Morse Code statement to translate. Separate letters with spaces and words with a ' | '" );
translateMe = input.next();
String [] morseChar = translateMe.split(" ");
for( int x = 0; x < morseChar.length; x++)
{
String letter = morseChar[ x ];
for ( int index = 0; index < morse.length; index++ )
{
if(morse [ index ].equals(letter))
{
System.out.print(english[ index ]); // Display character at matching index position of English array to show translation
}
}
}
}
else
{
System.out.println("Please enter an English statement to translate:");
translateMe = input.next();
translateMe = translateMe.toLowerCase();
String [] englishChar = translateMe.split("(?!^)");
for ( int x = 0; x < englishChar.length; x++)
{
String letter = englishChar [ x ];
for (int index = 0; index < english.length; index++)
{
if( english [index].equals( letter ))
{
System.out.print(morse[index] + " "); // Display Morse Code array character at matching index position to show translation
}
}
}
}
}
}
我一直在用这个词
to be
及其摩尔斯电码对应物
- --- | -… .
作为测试用语。当我尝试用这个短语将英语翻译成摩尔斯电码时,我得到了
... -.
s 和 n
作为输出。当我尝试将摩尔斯电码转换为英语时,我得到了
u
作为输出。morse[A]
我已经检查了我的两个字符串数组,以确保english[A]
它们处于相同的索引位置等等,这些都很好。我想不出还有什么会导致这个问题的。
编辑:知道我正在使用 IntelliJ IDEA 15 可能会有所帮助