簡體   English   中英

如何在莫爾斯電碼翻譯器中迭代 hashmap?

[英]How to iterate hashmap in a morse code translator?

我有一個項目,我需要從用戶那里獲取輸入,將其轉換為莫爾斯電碼,反之亦然。

我必須使用 hashmap,我的代碼看起來像這樣。 它並沒有真正起作用。 我無法理解如何在 class engToMorse 上打印我從用戶那里獲得的輸入。

我也嘗試查看其他類似的問題,但找不到任何可以解決我的問題的東西。

編輯1:通過將.toLowerCase 更改為.toUpperCase,它確實有效,但僅適用於一個詞。 我將如何使它適用於多個單詞,例如一個句子。 Edit2:通過添加 translate.put(' ', " "); 來解決這個問題。 我現在如何將莫爾斯語轉換為英語? 是同一個想法嗎?

public static void main(String[]args){
    HashMap<Character,String> translations=new HashMap<Character,String>();
    translations.put('A', ".-");
    translations.put('B', "-...");
    translations.put('C', "-.-.");
    translations.put('D', "-..");
    translations.put('E', ".");
    translations.put('F', "..-.");
    translations.put('G', "--.");
    translations.put('H', "....");
    translations.put('I', "..");
    translations.put('J', ".---");
    translations.put('K', "-.-");
    translations.put('L', ".-..");
    translations.put('M', "--");
    translations.put('N', "-.");
    translations.put('O', "---");
    translations.put('P', ".--.");
    translations.put('Q', "--.-");
    translations.put('R', ".-.");
    translations.put('S', "...");
    translations.put('T', "-");
    translations.put('U', "..-");
    translations.put('V', "...-");
    translations.put('W', ".--");
    translations.put('X', "-..-");
    translations.put('Y', "-.--");
    translations.put('Z', "--..");
    translations.put('0', "-----");
    translations.put('1', ".----");
    translations.put('2', "..---");
    translations.put('3', "...--");
    translations.put('4', "....-");
    translations.put('5', ".....");
    translations.put('6', "-....");
    translations.put('7', "--...");
    translations.put('8', "---..");
    translations.put('9', "----.");
    translations.put(' ', "   ");
    Scanner scan=new Scanner(System.in);
    System.out.println("Welcome to the translator. Type 1 for English to Morse or type 2 for Morse to English: ");
    int choice=scan.nextInt();
    if(choice==1)
       engToMorse(translations);
    else if(choice==2)
        morseToEng(translations);
    else{
        System.out.println("Invalid Input!");
    }
  
}
public static void engToMorse(HashMap<Character,String> translations){
    
    Scanner scan=new Scanner(System.in);
    System.out.println("Please enter the sentence that you want to translate to Morse here: ");
    String sentence=scan.nextLine().toUpperCase();
    int i=0;
    while(i<sentence.length()){
        System.out.printf(translations.get(sentence.charAt(i)));
        i++;
    }
    

您的 hashmap 翻譯的鍵是大寫的,您將“句子”中的所有字符都轉換為小寫。 當你得到 hashmap 中的元素時,將它改回大寫是最簡單的方法。

while(i<sentence.length()){
    System.out.println(translations.get(Character.toUpperCase(sentence.charAt(i))));
    i++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM