【问题标题】:Morse Code Translator - Can't seem to convert from morse-to-english accurately莫尔斯电码翻译器 - 似乎无法准确地将莫尔斯电码转换为英语
【发布时间】:2014-09-18 05:49:54
【问题描述】:

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

问题如下:

“编写一个程序,读取一个英语短语并将该短语编码为摩尔斯电码,或者读入一个摩尔斯电码短语并将该短语转换为英语。在每个摩尔斯电码字母之间使用一个空格每个摩尔斯电码词之间有三个空格。”

我遇到的问题是上面的粗体句子。我已经让程序的其余部分从英语到莫尔斯语工作,但反过来它只是搞砸了。

这是我所知道的情况:

字母 'e' 的摩尔斯电码是 '.''t''-',而字母 'a''.-',在我当前的代码中,如果您要输入 '.-'在 morse-to-english 区域,它会将翻译返回为 '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();
              }

      }
}

}

【问题讨论】:

  • 这里有一个提示 - 如果在你的 morseArray 中你在每个字符串之后包含一个空格,例如“.-”而不是“.-”
  • 看看 String.split() 和正则表达式。您想通过任意数量的空格字符 (\\s+) 将英语句子拆分为单词,然后遍历每个单词的每个字符。莫尔斯文本你想用 3 个空格 (\\s{3}) 分割成单词,然后用一个空格 (\\s) 将单词分割成字符
  • Kharyam - 尝试过,它导致输出完全空白! Radai - 现在研究 String.split()。我们没有在课堂上讨论过这个问题,但它似乎确实可以解决这个问题。谢谢!

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


【解决方案1】:

我使用上面给出的建议解决了我的问题。我最终使用了 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();
              }

      }
}

}

【讨论】:

    【解决方案2】:

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

    .- -... -.-.
    

    意思是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 数据结构更容易使用(可能这是不允许的),但您不需要线性搜索来查找每个字母的翻译:

    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);
    }
    

    然后为摩尔斯 -> 英语和英语 -> 摩尔斯翻译实现它:

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

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

    这样你可以更好地构建你的代码:)

    【讨论】:

    • 虽然我们刚刚开始使用接口,但不幸的是,我只能为这个特定的任务提交一个 Java 文件。我也不熟悉 Map 数据结构,但我知道我可以在此分配中使用的唯一数据结构是数组(单个或多个)。不过,我肯定会考虑使用 String.split() ,这听起来确实像是我想要走的路线。我真的很感谢你的帮助,我觉得我在绕圈子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多