2017-07-25 145 views
-2

//我只是一個初學者,這是我的第一個程序,它工作正常,但有什麼辦法可以讓它變得更好嗎?英文到莫爾斯碼轉換器,我怎樣才能使它更有效率?

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

您可以正確縮進它。 – khelwood

+0

這不是一個特定的編程問題。 –

+5

我相信這種類型的問題在[代碼評論](https://codereview.stackexchange.com/)堆棧交換 – hrust

回答

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:

「通過這樣做,你是信的ASCII值轉換‘a’到一個int(97,我認爲)這樣做是讓你變身翻譯的ASCII值[j]改爲0的比例值,而不是從97開始。這允許您直接使用數組,因爲它們全部從0開始。在恢復中,您將ASCII值向左移動以便能夠直接使用數組。

+0

嗨,你真了不起,我只是不明白主要的東西。 你能讓我明白這條線怎麼執行? morseCode [translate [j] - (int)'a'] –

+0

@TosifKhan通過這樣做,您正在將字母'a'的ASCII值轉換爲int(97,我認爲)。這樣做可以讓您將'translate [j]'的ASCII值轉換爲0的比例值,而不是從97開始。這允許您直接使用數組,因爲它們全部從0開始。在恢復中,您將ASCII值移動到左邊可以直接使用數組。 – Shirkam

+0

另外,@Cylexx記住你的答案是全功能的,因爲在小寫字符之後'',''和'|「不是。事實上,'',''在ASCII表中是44,'|'是124,所以它們需要一些特殊的處理。 – Shirkam