Java
Java

 

Introduction

Morse code is a method of encoding text characters into sequences of dots and dashes, where each letter or numeral is represented by a unique combination. It was widely used for telecommunication, especially in the early days of radio communication. In this program, we will create a tool that can translate text into Morse code and vice versa.

This program in Java will allow users to input text and get the corresponding Morse code translation. Similarly, users can input Morse code (dots and dashes) and get the translated text. This tool will be useful for anyone interested in learning Morse code or in applications where communication needs to be encoded for security or efficiency.

Objective

The objective of this program is to create a simple Java application that:

  • Translates regular text into Morse code.
  • Translates Morse code back into regular text.
  • Handles both upper and lowercase letters, numbers, and common punctuation marks.
  • Accepts user input and outputs the translation in a readable format.

Code

import java.util.Scanner;

public class MorseCodeTranslator {

    // Define the mappings for Morse code
    private static final String[] MORSE_CODE = {
        ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
        "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-",
        ".....", "-....", "--...", "---..", "----.", ".-.-.-", "--..--", "..--..", ".----.", "-.-.--", "-..-.", "-....-", "..--.-",
        ".-.-.", "---...", "-.-.-.", "-...-", ".-..-.", ".--.-."
    };

    // Define the alphabet and numbers that correspond to Morse code
    private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final String PUNCTUATION = ".,-?'!/()&:;=+-_$@";

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

        System.out.println("Morse Code Translator");
        System.out.println("Choose an option: ");
        System.out.println("1. Text to Morse Code");
        System.out.println("2. Morse Code to Text");
        System.out.print("Enter your choice (1 or 2): ");
        int choice = scanner.nextInt();
        scanner.nextLine();  // Consume the newline

        if (choice == 1) {
            // Text to Morse code
            System.out.print("Enter text to translate to Morse code: ");
            String text = scanner.nextLine().toUpperCase();
            String morseCode = textToMorse(text);
            System.out.println("Morse Code: " + morseCode);
        } else if (choice == 2) {
            // Morse code to Text
            System.out.print("Enter Morse code to translate to text: ");
            String morse = scanner.nextLine();
            String text = morseToText(morse);
            System.out.println("Text: " + text);
        } else {
            System.out.println("Invalid choice. Please enter 1 or 2.");
        }

        scanner.close();
    }

    // Method to convert text to Morse code
    private static String textToMorse(String text) {
        StringBuilder morseCode = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == ' ') {
                morseCode.append("   "); // Separate words with 3 spaces
            } else {
                int index = ALPHABET.indexOf(c);
                if (index != -1) {
                    morseCode.append(MORSE_CODE[index] + " ");
                } else {
                    // Check for punctuation marks
                    int punctuationIndex = PUNCTUATION.indexOf(c);
                    if (punctuationIndex != -1) {
                        morseCode.append(MORSE_CODE[ALPHABET.length() + punctuationIndex] + " ");
                    }
                }
            }
        }
        return morseCode.toString().trim();
    }

    // Method to convert Morse code to text
    private static String morseToText(String morse) {
        StringBuilder text = new StringBuilder();
        String[] morseArray = morse.split("   "); // Separate words by 3 spaces
        for (String word : morseArray) {
            String[] morseLetters = word.split(" "); // Separate letters by 1 space
            for (String letter : morseLetters) {
                int index = findMorseIndex(letter);
                if (index != -1) {
                    if (index < ALPHABET.length()) {
                        text.append(ALPHABET.charAt(index));
                    } else {
                        text.append(PUNCTUATION.charAt(index - ALPHABET.length()));
                    }
                }
            }
            text.append(" ");
        }
        return text.toString().trim();
    }

    // Helper method to find the index of a Morse code symbol
    private static int findMorseIndex(String morse) {
        for (int i = 0; i < MORSE_CODE.length; i++) {
            if (MORSE_CODE[i].equals(morse)) {
                return i;
            }
        }
        return -1; // If the Morse code symbol is not found
    }
}

Program Explanation

This Java program translates text into Morse code and vice versa. Here’s a breakdown of the key components:

  • Morse Code Mappings: The program uses two arrays, MORSE_CODE and ALPHABET, to map each letter and number to its Morse code equivalent. Additionally, the program handles punctuation marks through the PUNCTUATION array.
  • Text to Morse Code: The textToMorse method converts a given text string into Morse code by looking up each character in the ALPHABET array and appending the corresponding Morse code from the MORSE_CODE array.
  • Morse Code to Text: The morseToText method works in reverse, converting Morse code back into readable text. It splits the input by spaces to separate the words and then decodes each Morse code symbol into its respective letter or punctuation mark.
  • User Interaction: The program prompts the user to choose whether they want to convert text to Morse code or Morse code to text. Depending on the user’s choice, the program executes the corresponding method and displays the result.

How to Run the Program

To run this program, follow these steps:

  1. Save the code in a file named MorseCodeTranslator.java.
  2. Open a terminal or command prompt and navigate to the directory where the file is saved.
  3. Compile the program with the Java compiler:
    javac MorseCodeTranslator.java
  4. Run the program:
    java MorseCodeTranslator
  5. The program will ask you to choose an option and then either convert text to Morse code or vice versa based on your input.
© 2024 Learn Programming

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)