【问题标题】:Morse Code Conversion using Java使用 Java 进行摩尔斯电码转换
【发布时间】:2013-02-12 15:49:19
【问题描述】:

我正在尝试学习 Java 中的哈希图和二维数组。我们有一个任务,因为有一个扫描仪可以接受字符串并将其转换为莫尔斯电码。我们使用的代码基于一个充满 if 语句的方法,但我想了解如何使用列表、哈希图或二维数组来执行类似的操作。我的代码如下:

import java.util.*;

public class MorseConversion 
{


public static void main(String[] args) 
{

    Scanner userInput = new Scanner(System.in); 
    System.out.println("Please enter a phrase to convert to morse code: ");
    String userString = userInput.nextLine();
    System.out.println("");
    System.out.println(stringConvert(userString));
}


public static String stringConvert(String userString)
{
    String currentChar;
    String getMorseChar;
    String convertedString = "";

    for (int i = 0; i < userString.length(); i++)
    {
        //Get character at i position
        currentChar = userString.charAt(i) + "";  

        //convert character to morse code
        getMorseChar = convert(currentChar);

        //seperate words with the | symbol
        if (getMorseChar.equals(" "))
        {
            convertedString = convertedString + "  |  ";
        } 

        else 
        {
            //concat the converted letter
            convertedString = convertedString + getMorseChar;

            //Add a space between each letter
            if (!getMorseChar.equals(" ")) 
            {
                convertedString = convertedString + " ";
            }   
        }           
    }

    return convertedString;

}
 public static String convert (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;  
    }  

 }

我这样做完全是出于好奇。我已经意识到像这样的冗余是一个巨大的禁忌。提前致谢!

【问题讨论】:

    标签: java list hashmap encode


    【解决方案1】:

    这是优化后的代码,可以清楚地理解二维数组

    public class MorseCode {
    public static Scanner sc;
    public static void main(String args[]) throws IOException  //Input Output Exception is added to cover the BufferedReader 
    {
        int option = 0;
        String sentence = "",answer = "",answer1 = "";
         char[] 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',
                 ',', '.', '?' };   //Defining a Character Array of the English Letters numbers and Symbols so that we can compare and convert later 
    
         String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", 
                    ".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.",
                    "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
                    "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
                    "-----", "--..--", ".-.-.-", "..--.." };  //Defining an Array of String to hold the Morse Code value of Every English Letter,Number and Symbol in the same order as that of the character Array  
        sc = new Scanner(System.in);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println(">>>>Welcome to MorseCode Software<<<<");
        System.out.println("");
        do
        {
        System.out.println("-->Enter the Option Corresponding to the Task you want to Perform ");
        System.out.println("->1.Generate Morse Code<- OR ->2.Generate English Language<- OR ->3.Exit ");
        System.out.print("->");
        while(!sc.hasNextInt())  //Repeat Until the next Item is an Integer i.e Until the Next Item is an Integer Keep on Repeating it 
        {//NOTE- The hasnext() function is also used when we are using the Iterator where the next input is always checked and then if it is valid it is allowed to be entered 
            System.out.println("");
            System.err.println("-->ERROR<-->Enter Digits Only<--");
            System.out.print("->");
            sc.next();   //Repeat and Discard the previous Inputs which are not valid 
        }
        option = sc.nextInt();
        switch(option)
        {
        case 1:
        {
            System.out.println("");
            System.out.println("-->Enter the Sentence that you want to Transmit Using the Morse Code ");
            System.out.print("->");
            sentence = br.readLine();
            System.out.println("");
            sentence = sentence.toLowerCase(); //Because morse code is defined only for the lower case letters and the numbers and the Symbols will remain the Same
            char[] morsec = sentence.toCharArray();
            for(int i = 0; i < morsec.length;i++)  //The loop will run till i is less than the number of characters in the Sentence because Every Character needs to Be Converted into the Respective Morse Code 
            {//For Every Letter in the User Input Sentence
                for(int j = 0;j<english.length;j++)   //For Every Character in the morsec array we will have to traverse the entire English Array and find the match so that it can be represented 
                {
                    if(english[j] == morsec[i])  //If the Character Present in English array is equal to the character present in the Morsec array then Only Execute 
                    {//Always remember that the condition in the Inner loop will be the first to be Equated in the If Statement because that will change until the characters match 
                        answer = answer + morse[j] + " ";  //After Every Letter is generated in the Morse Code we will give a Space 
                    }  //Since the Letters in the English char and the symbols present in the morse array are at the Same Index 
                }
            }
            System.out.println("-->The Morse Code Translation is:- ");
            System.out.print(">> ");
            System.out.println(answer);
            System.out.println("");
            break;
        }
        case 2:
        {
            System.out.println("");
            System.out.println("-->Enter the Morse Code and After Every Letter add Space in Between ");
            System.out.print("-> ");
            sentence = br.readLine();
            System.out.println("");
            String[] morsec = sentence.split(" ");   //To use the split function to Convert Every Morse Code String as a Separate Entry in the STring array 
            for(int i = 0;i < morsec.length;i++)
            {//For Every morse code Letter Entered 
            //Remember - We are Splitting on the Basis of the space     
                for(int j = 0;j < morse.length;j++)
                {
                    if(morse[j].equals(morsec[i]))  //When you are comparing the String you have to Do this and not == 
                    {
                        answer1 = answer1 + english[j];  //Since the characters in the Morse array and the English Array are in the Same Index
                    }
                }
            }
            System.out.println("-->The English Language Translation is:- ");
            System.out.print(">> ");
            System.out.println(answer1);
            System.out.println("");
            break;
        }
        case 3:
        {
            System.out.println("");
            System.out.println(">>Thank you For Using this Service<<");
            System.out.println("");
            break;
        }
        default:
        {
            System.err.println("-->ERROR<-->Invalid Option Entered<--");
            System.out.println("");
            break;
        }
        }
        }
        while(option!=3);
        }
    

    }

    希望代码没有混乱

    【讨论】:

      【解决方案2】:

      更简单的方法是使用初始化程序将字符加载到哈希映射中,使用字母作为键。然后,当您循环输入字符串中的字符时,您只需执行

      在你上课的开始做这样的事情:

      private static HashMap<String, String> codes = new HashMap<String, String>();
          static{
              codes.put("a", ".-");
              codes.put("b", "-...");
              bla bla bla
          }
      

      然后在你有的循环中

      //convert character to morse code
              getMorseChar = convert(currentChar);
      

      你会的

      getMorseChar = code.get(currentChar.toLowerCase());
      

      不再有讨厌的 elseif 语句。

      【讨论】:

      • 这正是我想做的!我只是不太确定如何实现它。如果你能让我开始,那将非常有帮助,谢谢!
      • 符号灯在什么时候打开和在什么时候关闭。
      猜你喜欢
      • 2010-12-23
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多