我見過很多關於摩爾斯電碼翻譯器的問題,並且看過很多,但是在所有這些問題中,建議的答案都會給我提供相同的錯誤輸出。代碼背後的想法是能夠使用數組將Morse Code翻譯成英文,反之亦然。我的代碼如下:爲什麼我的Java Morse Code翻譯器給我錯誤的輸出?
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
這適用於英語莫爾斯,但莫爾斯英語我錯過了'b' – Jes
對不起傑斯,你是什麼意思錯過'B'? –
啊,對不起,我的'要'測試(從莫爾斯到英文)的'b'缺失。我一直在用它作爲測試短語。 – Jes