java - 如何在摩尔斯电码翻译器中迭代哈希图?
问题描述
我有一个项目,我需要从用户那里获取输入,将其转换为莫尔斯电码,反之亦然。
我必须使用哈希图,我的代码看起来像这样。它并没有真正起作用。我无法理解如何在 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 中获取元素时将其更改回大写是最简单的方法。
while(i<sentence.length()){
System.out.println(translations.get(Character.toUpperCase(sentence.charAt(i))));
i++;
}