2015-06-17 4 views
2

Моя проблема прямо сейчас заключается в том, чтобы работать с «кодом Морзе на английском». первая часть, которая преобразует английский в морсы, работает отлично. Я знаю, что это было задано раньше, но я не могу понять, что я делаю неправильно. Я знаю, что мне нужен раскол где-то, но я просто не уверен, куда его поместить в код. прямо сейчас морсов к английской части даже не будет конвертировать один символ. Любая помощь будет высоко ценится.Код Морзе на английском языке

import java.util.Scanner; 

public class MorseCode2 { 
    public static void main (String [] args) 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Would you like to convert English to Morse (yes or no)? "); 
     String answer = input.nextLine(); 
     if(answer.equals("yes")) 
     { 
     System.out.println("Please enter the text you want to translate into Morse code: "); 
     String english = input.nextLine(); 
     System.out.println(stringToMorse(english)); 
     } 

     if (answer.equalsIgnoreCase("no")) 
     { 
      System.out.print("Morse to English? "); 
      String answer2 = input.nextLine(); 
      if (answer2.equalsIgnoreCase("yes")) 
      { 
       System.out.println("Please enter the Morse code you want to translate into English: "); 
       String code = input.nextLine(); 
       System.out.println(stringToEnglish(code)); 
      } 
     } 
    } 

    public static String encode (String toEncode) 
    { 
     String morse = toEncode; 

     if (toEncode.equalsIgnoreCase("a")) 
      morse = ".-"; 
     if (toEncode.equalsIgnoreCase("b")) 
      morse = "-..."; 
     if (toEncode.equalsIgnoreCase("c")) 
      morse = "-.-."; 
     if (toEncode.equalsIgnoreCase("d")) 
      morse = "-.."; 
     if (toEncode.equalsIgnoreCase("e")) 
      morse = "."; 
     if (toEncode.equalsIgnoreCase("f")) 
      morse = "..-."; 
     if (toEncode.equalsIgnoreCase("g")) 
      morse = "--."; 
     if (toEncode.equalsIgnoreCase("h")) 
      morse = "...."; 
     if (toEncode.equalsIgnoreCase("i")) 
      morse = ".."; 
     if (toEncode.equalsIgnoreCase("j")) 
      morse = ".---"; 
     if (toEncode.equalsIgnoreCase("k")) 
      morse = "-.-"; 
     if (toEncode.equalsIgnoreCase("l")) 
      morse = ".-.."; 
     if (toEncode.equalsIgnoreCase("m")) 
      morse = "--"; 
     if (toEncode.equalsIgnoreCase("n")) 
      morse = "-."; 
     if (toEncode.equalsIgnoreCase("o")) 
      morse = "---"; 
     if (toEncode.equalsIgnoreCase("p")) 
      morse = ".--."; 
     if (toEncode.equalsIgnoreCase("q")) 
      morse = "--.-"; 
     if (toEncode.equalsIgnoreCase("r")) 
      morse = ".-."; 
     if (toEncode.equalsIgnoreCase("s")) 
      morse = "..."; 
     if (toEncode.equalsIgnoreCase("t")) 
      morse = "-"; 
     if (toEncode.equalsIgnoreCase("u")) 
      morse = "..-"; 
     if (toEncode.equalsIgnoreCase("v")) 
      morse = "...-"; 
     if (toEncode.equalsIgnoreCase("w")) 
      morse = ".--"; 
     if (toEncode.equalsIgnoreCase("x")) 
      morse = "-..-"; 
     if (toEncode.equalsIgnoreCase("y")) 
      morse = "-.--"; 
     if (toEncode.equalsIgnoreCase("z")) 
      morse = "--.."; 
     if (toEncode.equalsIgnoreCase("0")) 
      morse = "-----"; 
     if (toEncode.equalsIgnoreCase("1")) 
      morse = ".----"; 
     if (toEncode.equalsIgnoreCase("2")) 
      morse = "..---"; 
     if (toEncode.equalsIgnoreCase("3")) 
      morse = "...--"; 
     if (toEncode.equalsIgnoreCase("4")) 
      morse = "....-"; 
     if (toEncode.equalsIgnoreCase("5")) 
      morse = "....."; 
     if (toEncode.equalsIgnoreCase("6")) 
      morse = "-...."; 
     if (toEncode.equalsIgnoreCase("7")) 
      morse = "--..."; 
     if (toEncode.equalsIgnoreCase("8")) 
      morse = "---.."; 
     if (toEncode.equalsIgnoreCase("9")) 
      morse = "----."; 
     if (toEncode.equalsIgnoreCase(".")) 
      morse = ".-.-"; 
     if (toEncode.equalsIgnoreCase(",")) 
      morse = "--..--"; 
     if (toEncode.equalsIgnoreCase("?")) 
      morse = "..--.."; 

     return morse; 
    } 

    public static String decode (String toEncode) { 
     String morse = toEncode; 

     if (toEncode.equalsIgnoreCase(".-")) 
      morse = "a"; 
     if (toEncode.equalsIgnoreCase("-...")) 
      morse = "b"; 
     if (toEncode.equalsIgnoreCase("-.-.")) 
      morse = "c"; 
     if (toEncode.equalsIgnoreCase("-..")) 
      morse = "d"; 
     if (toEncode.equalsIgnoreCase(".")) 
      morse = "e"; 
     if (toEncode.equalsIgnoreCase("..-.")) 
      morse = "f"; 
     if (toEncode.equalsIgnoreCase("--.")) 
      morse = "g"; 
     if (toEncode.equalsIgnoreCase("....")) 
      morse = "h"; 
     if (toEncode.equalsIgnoreCase("..")) 
      morse = "i"; 
     if (toEncode.equalsIgnoreCase(".---")) 
      morse = "j"; 
     if (toEncode.equalsIgnoreCase("-.-")) 
      morse = "k"; 
     if (toEncode.equalsIgnoreCase(".-..")) 
      morse = "l"; 
     if (toEncode.equalsIgnoreCase("--")) 
      morse = "m"; 
     if (toEncode.equalsIgnoreCase("-.")) 
      morse = "n"; 
     if (toEncode.equalsIgnoreCase("---")) 
      morse = "o"; 
     if (toEncode.equalsIgnoreCase(".--.")) 
      morse = "p"; 
     if (toEncode.equalsIgnoreCase("--.-")) 
      morse = "q"; 
     if (toEncode.equalsIgnoreCase(".-.")) 
      morse = "r"; 
     if (toEncode.equalsIgnoreCase("...")) 
      morse = "s"; 
     if (toEncode.equalsIgnoreCase("-")) 
      morse = "t"; 
     if (toEncode.equalsIgnoreCase("..-")) 
      morse = "u"; 
     if (toEncode.equalsIgnoreCase("...-")) 
      morse = "v"; 
     if (toEncode.equalsIgnoreCase(".--")) 
      morse = "w"; 
     if (toEncode.equalsIgnoreCase("-..-")) 
      morse = "x"; 
     if (toEncode.equalsIgnoreCase("-.--")) 
      morse = "y"; 
     if (toEncode.equalsIgnoreCase("--..")) 
      morse = "z"; 
     if (toEncode.equalsIgnoreCase("-----")) 
      morse = "0"; 
     if (toEncode.equalsIgnoreCase(".----")) 
      morse = "1"; 
     if (toEncode.equalsIgnoreCase("..---")) 
      morse = "2"; 
     if (toEncode.equalsIgnoreCase("...--")) 
      morse = "3"; 
     if (toEncode.equalsIgnoreCase("....-")) 
      morse = "4"; 
     if (toEncode.equalsIgnoreCase(".....")) 
      morse = "5"; 
     if (toEncode.equalsIgnoreCase("-....")) 
      morse = "6"; 
     if (toEncode.equalsIgnoreCase("--...")) 
      morse = "7"; 
     if (toEncode.equalsIgnoreCase("---..")) 
      morse = "8"; 
     if (toEncode.equalsIgnoreCase("----.")) 
      morse = "9"; 
     if (toEncode.equalsIgnoreCase("|")) 
      morse = ""; 

     return morse; 
    } 

    public static String stringToMorse(String text) 
    { 

     String newText = ""; 
     String selectedChar; 
     String convertedChar; 
     for (int i = 0; i < text.length(); i++) 
     { 

      //Select the next character 
      selectedChar = text.charAt(i) + ""; 

      // Convert the character 
      convertedChar = encode(selectedChar); 

      if (convertedChar.equals(" ")) // " " separates each word represented in english code 
      { 
       newText = newText + "| "; 
      } 
      // Add the converted text, and add a space 
      else 
      { 
       newText = newText + convertedChar; 
       if (!convertedChar.equals(" ")) 
       { 
        newText = newText + " "; 
       } 
      } 
     } 

     return newText; 
    } 

    public static String stringToEnglish(String text) 
    { 
     String newMorse = ""; //sets string for newMorse 
     String selectedMorse; //sets string for selectedMorse 
     String convertedMorse; //sets string for convertedMorse 
     for (int i = 0; i < text.length(); i++) 
     { 

      //Select the next character 
      selectedMorse = text.charAt(i) + ""; 

      // Convert the character 
      convertedMorse = encode(selectedMorse); 

      if (convertedMorse.equals("| ")) // "|" separates each word represented in morse code 
      { 
       newMorse = newMorse + " "; 
      } 
      // Add the converted text, and add a space 
      else 
      { 
       newMorse = newMorse + convertedMorse; 
       if (!convertedMorse.equals(" ")) 
       { 
        newMorse = newMorse + " "; 
       } 
      } 
     } 

     return newMorse; 
    } 

} 
+0

Вы могли бы хотеть рассмотреть что-то вроде приставкой на основе сопоставления, если у вас нет места в вашем Морзе. Потребляйте персонажа, выполняйте поиск в чем-то вроде trie, потребляйте рядом до матча. Я не уверен, что код Морзе может иметь несоответствие, когда употребление префикса слишком жадно приведет к несоответствию позже. Если это так, вам может потребоваться отступить. – hexafraction

+0

Чтобы исправить вашу непосредственную проблему, вам, вероятно, следует называть 'decode (selectedMorse);' вместо 'encode' в' stringToEnglish'. Кроме того, вы не можете использовать 'text.charAt (i)' там, потому что один код Морзе состоит из нескольких символов. –

+1

Код Морзе, без какого-либо разделителя между кодами символов, является неоднозначным. См. Http://cs.stackexchange.com/questions/34067/is-morse-code-without-spaces-uniquely-decipherable – hatchet

ответ

2

Вы, вероятно, хотите что-то вроде этого:

public static String stringToEnglish(String text) 
{ 
    String newEnglish = ""; //sets string for newEnglish 
    String selectedEnglish; //sets string for selectedEnglish 
    String convertedEnglish; //sets string for convertedEnglish 
    String[] morseChars = text.split(" "); 
    for (int i = 0; i < morseChars.length; i++) 
    { 
     //Select the next Morse character 
     selectedEnglish = morseChars[i]; 
     boolean endsWithWordSeparator = selectedEnglish.endsWith("|"); 
     if(endsWithWordSeparator) selectedEnglish = selectedEnglish.substring(0, selectedEnglish.length() - 1); 
     // Convert the string 
     convertedEnglish = decode(selectedEnglish); 

     newEnglish = newEnglish + convertedEnglish; 
     if (endsWithWordSeparator) 
     { 
      newEnglish = newEnglish + " "; 
     } 
    } 

    return newEnglish; 
} 
+0

Не обращайте на это внимание. не возражаете ли вы объяснить, что вы сделали для моих целей обучения? – Cfs0004

+0

Коды Морзе - это набор из 2-5 символов, разделенных пробелами, поэтому сначала разделяем строку пробелами, а затем декодируем каждый, но сначала вынимаем '|' в конце, если таковые имеются, что указывает на разрыв слова. Вот и все. – Diego

Смежные вопросы