我需要幫助將莫爾斯電碼轉換爲英文。我已經編寫並測試了將英文翻譯成莫爾斯的代碼。我的主要問題是在將摩爾斯電碼中的所有字符翻譯成英文字符之前將它們合併在一起,如果這樣做合理的話。將多個字符轉換爲一個
例如:「。」轉化爲E和......轉化爲S,但我不想翻譯開始,直到它到達...
一些規則 -Spaces用來分隔莫爾斯快報 - |用作分隔符分隔單詞 -Cant使用的HashMap :(
這裏是我的代碼
import java.util.Arrays;
import javax.swing.JOptionPane;
public class test3
{
public static void main (String [] args)
{
String s1 = "Morse";
// Decide whether Morse code or English
String decide = JOptionPane.showInputDialog("Enter 'English' for Morse to English code translation and 'Morse' for English to Morse code translation. Pay attention to Caps.");
// Enter String & decide whether to convert to Morse or English
String phrase = JOptionPane.showInputDialog("Enter the words you wish to translate.");
if (decide.equals(s1))
toMorse(phrase);
else
toEnglish(phrase);
}
// Translate to Morse
public static void toMorse(String preTranslation)
{
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","1","2","3","4","5","6","7","8","9","0"};
String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..", ".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--..",".----","..---","...--","....-",".....","-....","--...","---..","----.","-----"};
// Remove uppercase
String preTrans = preTranslation.toLowerCase();
// Deletes spaces
String phraseWithDelimiter = preTrans.replace(" ", "|");
String[] translation = new String[phraseWithDelimiter.length()];
String[] delimiter = {"|"};
// Translate
for (int arrayVar = 0, transArrayVar = 0, subStringVarB = 0, subStringVarE = 1; transArrayVar < phraseWithDelimiter.length();)
{
if(phraseWithDelimiter.substring(subStringVarB, subStringVarE).equals(delimiter[0]))
{
translation[transArrayVar] = delimiter[0];
transArrayVar++;
subStringVarB++;
subStringVarE++;
}
else if (phraseWithDelimiter.substring(subStringVarB, subStringVarE).equals(english[arrayVar]))
{
translation[transArrayVar] = morse[arrayVar];
transArrayVar++;
subStringVarB++;
subStringVarE++;
arrayVar = 0;
}
else
{
arrayVar++;
if (arrayVar == 35)
{
arrayVar = 0;
subStringVarB++;
subStringVarE++;
transArrayVar++;
}
}
}
String morseSeparator = new String(" ");
arrayToString (translation, morseSeparator);
}
//Convert array to string and print translation
public static void arrayToString(String[] trans, String separator)
{
String result = "";
if (trans.length > 0)
{
result = trans[0]; // start with the first element
for (int i = 1; i < trans.length; i++)
result = result + separator + trans[i];
}
System.out.println(result);
}
// unfinished
public static void toEnglish(String preTranslation)
{
}
我在想作出了聲明和分配莫爾斯電碼的每個字符到一個新的串,直到我達到一個空格,然後使用該測試,但我不知道如何做到這一點。
任何幫助表示讚賞感謝!
爲什麼不允許使用'HashMap'?那麼我會說使用'TreeMap',但我想你也不能使用它,對嗎?這個要求就像作業,如果是這樣的話,請添加相應的標籤。 – Thomas
在使用['String.split()'](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html)處理之前,您應該在管道和空間周圍分割莫爾斯輸入。 #split(java.lang.String中))。你會得到一個單詞列表,每個列表都是完整的莫爾斯字母列表;你可以很容易地比較這些字母和你的字母 – millimoose