Morse code converter

The problem

Morse code is a code where each letter of the English alphabet, each digit, and various punctuation characters are represented by a series of dots and dashes. Write a program that asks the user to enter a string, and then converts that string to Morse code. Use hyphens for dashes and periods for dots.

Breaking it down

In this exercise we will create a java hashmap and store the letter or digit as the key with the associated morse code as the value. We will ask the user to input a phrase, call toUpperCase() and loop through with java 8 foreach char element looking up the morse code value.

Create map

static Map<String, String> LETTER_TO_MORSE_CODE = new HashMap<>();

static {
    LETTER_TO_MORSE_CODE.put(" ", " ");
    LETTER_TO_MORSE_CODE.put(",", "--..--");
    LETTER_TO_MORSE_CODE.put(".", ".-.-.-");
    LETTER_TO_MORSE_CODE.put("?", "..--..");
    LETTER_TO_MORSE_CODE.put("0", "-----");
    ...
    LETTER_TO_MORSE_CODE.put("W", ".--");
    LETTER_TO_MORSE_CODE.put("X", "-..-");
    LETTER_TO_MORSE_CODE.put("Y", "-.--");
    LETTER_TO_MORSE_CODE.put("Z", "--..");
}

Main program

public static void main(String[] args) {

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Get a string from the user.
    System.out.println("Enter a string to convert to Morse code.");
    System.out.print("> ");

    // String to hold the user's input.
    String userInput = keyboard.nextLine();

    // close keyboard
    keyboard.close();

    // split string into array and upper case
    userInput
            .toUpperCase()
            .chars()
            .forEach(
                    s -> System.out.println(LETTER_TO_MORSE_CODE
                            .get(Character.toString((char) s))));
}

Output

Enter a string to convert to Morse code.
> leveluplunch
.-..
.
...-
.
.-..
..-
.--.
.-..
..-
-.
-.-.
....

Level Up

  • Verify what happens if someone enters a letter or a digit that isn't contained in the map. What should be the output to the user?
  • Rewrite the program without using java 8.