莫尔斯电码翻译 - 似乎无法准确地从莫尔斯语转换为英语

时间:2014-07-26 13:35:18

标签: java arrays for-loop while-loop nested-loops

所以我有一个到期的任务,我花了很多时间试图找出问题的一个特定部分,但一直没有提出任何问题。我终于放弃了#39;并决定来这里寻求一点帮助。

问题内容如下:

"编写一个程序,该程序读取英语短语并将该短语编码为摩尔斯电码或读入莫尔斯电码中的短语并将该短语转换为英语。 在每个莫尔斯代码字母和每个莫尔斯代码字之间的三个空格之间使用一个空白。"

我遇到麻烦的是上面的粗体句子。我已经完成了从英语到莫尔斯的其他程序,但反过来它只是搞砸了。

以下是我所知道的事情:

字母'' 的摩尔斯电码是'。' ' t& #39; ' - ' ,字母' a' &#39 ; .-' ,在我目前的代码中,如果您要在莫尔斯到英语区输入' .-' ,那么&# 39;要将翻译作为' et'返回,这是不对的。当它需要做的是读取整个点和破折点并试图找到它的等价物时,它会读取每个点和破折号。我认为问题中的一空白和三个空白是我弄乱的地方,但我无法解决如何实现这一点。我认为这意味着单个空白区域之前的所有内容都将被完整地读取,然后三空白空间将简单地翻译成单一空白以确保英语翻译可读作为句子。

这是我目前的代码。我是一名新的Java编程学生,并且被告知我必须使用数组来解决这个问题。谢谢:

import java.util.*;

public class MorseCode {

public static void main(String[] args)
{
      Scanner input = new Scanner(System.in);

      String userResponse = "";
      String english = "English";
      String morse = "Morse-Code";
      String phrase = "";
      String answer = "";
      int loop = 0;

      final String[] englishArray = {"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"};

      final String[] morseArray = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
                             ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
                             "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", " ", 
                             ".----", "..---", "...--", "....-", ".....", "-....", "--...", 
                             "---..", "----.", "-----"};

      while(loop == 0)
      {
          System.out.print("\nWould you like to enter a phrase in English or in Morse-code? ");
          userResponse = input.next();  

          while(!(userResponse.equalsIgnoreCase(english) || userResponse.equalsIgnoreCase(morse)))
          {
              System.out.println("\nInvalid response. \nPlease enter 'English' or 'Morse-code'.\n");
              System.out.print("Would you like to enter a phrase in English or in Morse-code? ");
              userResponse = input.next();
          }

          if(userResponse.equalsIgnoreCase(english))
          {
              System.out.print("\nPlease enter your English phrase: ");
              input.nextLine();
              phrase = input.nextLine();    

              System.out.println("\nYou entered: " + phrase);
              phrase = phrase.toUpperCase();
              System.out.print("In morse code, this is: ");

              for(int count = 0; count < phrase.length(); count++ )
              { 
                  for(int index = 0; index < englishArray.length; index++) 
                  { 
                      if(phrase.substring(count, (count+1)).equals(englishArray[index]))
                          System.out.print(morseArray[index] + " "); 
                  } 
              } 
          }
          else if(userResponse.equalsIgnoreCase(morse))
          {
              System.out.print("\nPlease enter your Morse-code phrase: ");
              input.nextLine();
              phrase = input.nextLine();    

              System.out.println("\nYou entered: " + phrase);
              System.out.print("In English, this is: ");

              for(int count = 0; count < phrase.length(); count++ )
              { 
                  for(int index = 0; index < morseArray.length; index++) 
                  { 
                      if(phrase.substring(count, (count+1)).equals(morseArray[index])) 
                          System.out.print(englishArray[index]); 
                  } 
              } 
          }
          loop++;

          System.out.print("\n\nWould you like to enter another phrase? (Y or N): ");
          answer = input.next();

          while(!(answer.equalsIgnoreCase("Y") || answer.equalsIgnoreCase("N")))
            {
                System.out.print("\nIncorrect input. Please enter either 'Y' or 'N'.");
                System.out.print("Would you like to create 20 sentences? (Y or N): ");
                answer = input.next();  
            }
          if(answer.equalsIgnoreCase("Y"))
          {
              loop = 0;
          }
          else
              {
                System.out.println("Program ended.");
                input.close();
              }

      }
}

}

2 个答案:

答案 0 :(得分:1)

莫尔斯语中的一个词看起来像这样:

.- -... -.-.

含义ABC。请注意,各个莫尔斯字符之间有空格。您应该尝试对输入进行标记,在这种情况下只需将字符串拆分为' '

String input = readFromSomewhere();
// individual characters, you can now look them up in your array.
String [] morseCharacters = input.split(" ");

此外,如果输入的是多个单词,那么您应首先获得单个单词,并从每个单词中获取单个莫尔斯字符:

String multiWordInput = readFromSomewhere();
String [] words = multiWordInput.split("   "); // 3 spaces between words
for (String word : words) {
    String [] morseChars = words.split(" ");
    // Character can be translated.
}

对于存储单个字符,我认为Map数据结构更容易使用(可能是不允许的),但您不需要线性搜索来查找每个字母的翻译:< / p>

Map <String, String> morseToAscii = new HashMap<String, String>();
morseToAscii.put(".-", "A");
morseToAscii.put("-...", "B");
morseToAscii.put("-.-.", "C");
// ...

这会将你的莫尔斯字母映射到英文字母,所以你在得到它们之后就可以这样查找你的字母了:

String letterA = morseToAscii.get(".-"); // returns "A"
String letterB = morseToAscii.get("-..."); // returns "B"
String letterC = morseToAscii.get("-.-."); // returns "C"
String notValid = morseToAscii.get("Not a morse letter"); // this will be null

此外,我不知道你是否有任何面向对象的背景,但为了避免代码变得不可读,我会将翻译逻辑与控制台的实际读数等分开......

所以如果我是你,我会创建一个用于翻译内容的通用界面:

interface Translator {
    String translate(String input);
    String translateCharacter(String character);
    String translateWord(String word);
}

然后为莫尔斯实现它 - &gt;英语和英语 - &gt;莫尔斯翻译:

class MorseToEnglishTranslator implements Translator {
    // implement the Morse -> English translation here
}

class EnglishToMorseTranslator implements Translator {
    // implement the English -> Morse translation here 
}

通过这种方式,您可以更好地构建代码:)

答案 1 :(得分:0)

我使用上面给出的建议解决了我的问题。我最终使用了String.split()。

感谢您的帮助! :)

import java.util.*;

public class MorseCode {

public static void main(String[] args)
{

      Scanner input = new Scanner(System.in);

      String userResponse = "";
      String english = "English";
      String morse = "Morse-Code";
      String morseChars = "";
      String morseMultiWords = "";
      String morseWords = "";
      String phrase = "";
      String answer = "";
      int loop = 0;

      final String[] englishArray = {"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"};

      final String[] morseArray = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
                             ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
                             "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", " ", 
                             ".----", "..---", "...--", "....-", ".....", "-....", "--...", 
                             "---..", "----.", "-----"};

      while(loop == 0)
      {   
          System.out.print("\nWould you like to enter a phrase in English or in Morse-code? ");
          userResponse = input.next();  


          while(!(userResponse.equalsIgnoreCase(english) || userResponse.equalsIgnoreCase(morse)))
          {
              System.out.println("\nInvalid response. \nPlease enter 'English' or 'Morse-code'.\n");
              System.out.print("Would you like to enter a phrase in English or in Morse-code? ");
              userResponse = input.next();
          }
          if(userResponse.equalsIgnoreCase(english))
          {
              System.out.print("\nPlease enter your English phrase: ");
              input.nextLine();
              phrase = input.nextLine();    

              System.out.println("\nYou entered: " + phrase.toUpperCase());
              phrase = phrase.toUpperCase();
              System.out.print("In morse code, this is: ");

              for(int count = 0; count < phrase.length(); count++ )
              { 
                  for(int index = 0; index < englishArray.length; index++) 
                  { 
                      if(phrase.substring(count, (count+1)).equals(englishArray[index]))
                          System.out.print(morseArray[index] + " "); 
                  } 
              } 
          }

          else if(userResponse.equalsIgnoreCase(morse))
          {
              System.out.print("\nPlease enter your Morse-code phrase: ");
              input.nextLine();
              phrase = input.nextLine();

               String[] morseMultipleWords = phrase.split("   ");

              System.out.println("\nYou entered: " + phrase);
              System.out.print("In English, this is: ");

              for(int i = 0; i < morseMultipleWords.length; i++)
              {
                  morseMultiWords = morseMultipleWords[i];

                  String[] morseCharacters = morseMultiWords.split(" ");

                  for(int j = 0; j < morseCharacters.length; j++)
                  {
                      morseChars += morseCharacters[j];


                      for(int index = 0; index < morseArray.length; index++) 
                      { 
                          if(morseChars.equals(morseArray[index])) 
                              morseWords += englishArray[index];
                      }
                      morseChars = "";
                  }
                  morseWords += " "; 
                  morseMultiWords = "";  
              }
              System.out.println(morseWords); 
          }
          loop++;

          System.out.print("\n\nWould you like to enter another phrase? (Y or N): ");
          answer = input.next();

          while(!(answer.equalsIgnoreCase("Y") || answer.equalsIgnoreCase("N")))
            {
                System.out.print("\nIncorrect input. Please enter either 'Y' or 'N'.");
                System.out.print("Would you like to create 20 sentences? (Y or N): ");
                answer = input.next();  
            }
          if(answer.equalsIgnoreCase("Y"))
          {
              morseWords = "";
              loop = 0;
          }
          else
              {
                System.out.println("Program ended.");
                input.close();
              }

      }
}

}

相关问题