Search code examples
javahashmapconvertersmorse-code

English to Morse code converter, how can I make it more efficient?


//I'm just a beginner, this is my first program, it's working fine but is there any way I can make it better?

import java.util.*;
public class NewClass1 {

public static void main(String[] args) {

Character alphabet [] = {'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', ' '};
String morseCode [] = {".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. ", "--. ", ".... ", ".. ", ".--- ", "-.- ", ".-.. ", "-- ", "-. ", "--- ", ".--. ", "--.- ", ".-. ", "... ", "- ", "..- ", "...- ", ".-- ", "-..- ", "-.-- ", "--.. ", "| "};

//putting alphabets and morsecode in HashMap
Map<Character, String> morseCodes = new HashMap<>();
for(int i = 0; i < alphabet.length; i++)
{
    morseCodes.put(alphabet[i], morseCode[i]);
}

//Took user input and converted it into LowerCase Character Array
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
char[] translate = input.toLowerCase().toCharArray();

//Translating user input(translate[]) using for loop
for(int j=0; j<input.length(); j++){
    System.out.print(morseCodes.get(translate[j]));
}
}
}

Solution

  • You code was good but I think this solution is more efficient

    import java.util.*;
    public class HelloWorld {
    
    public static void main(String[] args) {
    
          String morseCode [] = {".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. ", "--. ", ".... ", ".. ", ".--- ", "-.- ", ".-.. ", "-- ", "-. ", "--- ", ".--. ", "--.- ", ".-. ", "... ", "- ", "..- ", "...- ", ".-- ", "-..- ", "-.-- ", "--.. ", "| "};
    
           //Took user input and converted it into LowerCase Character Array
           Scanner sc = new Scanner(System.in);
           String input = sc.nextLine();
           char[] translate = (input.toLowerCase()).toCharArray();
    
           //Translating user input(translate[]) using for loop
           for (int j = 0; j < translate.length; j++) {
                System.out.print(morseCode[translate[j] - (int)'a']);
           }
    }
    }
    

    I removed the hashmap, this is efficient in some case but here no need this data structure.

    Explaination by @Shirkam :

    "By doing it, your are converting the ASCII value of the letter 'a' to an int (97, I think). Doing that allows you to transform ASCII value of translate[j] to a 0 scale value, instead starting in 97. This allows you to directly use the array as they all start in 0. In resume, you are moving ASCII values to the left to be able to use an array directly."