英语到摩尔斯电码转换器,我怎样才能让它更有效率?

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

//我只是一个初学者,这是我的第一个程序,它工作正常但是有什么办法可以让它变得更好吗?

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

你的代码很好,但我认为这个解决方案更有效

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

我删除了hashmap,这在某些情况下很有效,但这里不需要这个数据结构。

@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."