Tosif Khan Tosif Khan - 1 year ago 97
Java Question

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]));
}
}
}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download