有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在莫尔斯电码转换器中迭代hashmap?

我有一个项目,我需要从用户那里获得输入,将其转换为摩尔斯电码,反之亦然

我必须使用hashmap,我的代码如下所示。这真的不管用。我很难理解如何在类engToMorse上打印用户输入的内容

我也试着研究其他类似的问题,但我找不到任何可以解决我问题的方法

编辑1:通过更改。toLowerCase to。虽然如此,它确实有效,但只适用于一个词。我如何让它适用于多个单词,比如一个句子。 Edit2:通过添加翻译器解决了这个问题。放入(“”,”);。我现在该怎么把摩尔斯电码转换成英语呢?这是相同的想法吗

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

共 (1) 个答案

  1. # 1 楼答案

    你们的hashmap翻译有一个键是大写的,你们把“句子”中的所有字符都转换成小写。 在hashmap中获取元素时,将其改回大写是最简单的方法

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