Search code examples
javauser-interfacemorse-code

Morse Code Application (JAVA Gui)


I am attempting to create a gui application that reads english user input and translates to morse (http://ascii-table.com/morse-code.php). I have touched on the basic parts of the program so far. My question is; what is the best way of going about reading morse? should i create a text file to import the morse letters off or should i declare each of them inside the program to translate? Next question is how would i go about doing this? please refer to a tutorial if possible. Thanks for your time.


Solution

  • Since Morse Code is not likely to change, hard-coding the mapping of characters to code strings is a valid option:

    private static Map<Character,String> charToCode = new HashMap<Character,String>();
    {
        charToCode.put('A', ".-");
        charToCode.put('B', "-...");
        ...
        charToCode.put('Z', "--..");
    }
    

    This map lets you convert messages to code one character at a time:

    • Make a StringBuilder for the result
    • Go through characters of the input one character at a time. You can use charAt(i) for that
    • Convert the character to upper case
    • Use charToCode.get(upperChar) to look up the code representation of the character
    • Append the representation to the StringBuilder; append a space after it
    • Once the loop is over, convert StringBuilder to String, and put it on the label.