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

时间:2017-07-25 08:09:31

标签: java hashmap converter morse-code

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

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

1 个答案:

答案 0 :(得分:1)

您的代码很好,但我认为此解决方案效率更高

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的解释:

&#34;通过这样做,您正在转换字母的ASCII值&#39; a&#39;到一个int(97,我认为)。这样做允许您将translate [j]的ASCII值转换为0比例值,而不是从97开始。这允许您直接使用数组,因为它们都以0开始。在恢复中,您将ASCII值移动到左侧能够直接使用数组。&#34;