Guys, I have this question: I want to create a Morzian encoder using HashMap. I entered the entire Latin alphabet, made the text input function, but I do not know how to make the program read the text entered by the user and translate it into Morse. I assume that you need to use the if statement, but I do not know how. PS I'm new. Here is the code:

package teach; import java.util.Map; import java.util.HashMap; import java.util.Scanner; public class Teach { public static void main(String[] args) { Scanner in = new Scanner(System.in); String User=in.nextLine(); Map<String, String> hm = new HashMap<String, String>(); hm.put("a", ".-"); hm.put("b", "-..."); hm.put("c", "-.-."); hm.put("d", "-.."); hm.put("e","."); hm.put("f","..-."); hm.put("g","--."); hm.put("h","...."); hm.put("i",".."); hm.put("j",".---"); hm.put("k","-.-"); hm.put("l",".-.."); hm.put("m","--"); hm.put("n","-."); hm.put("o","---"); hm.put("p",".--."); hm.put("q","--.-"); hm.put("r",".-."); hm.put("s","..."); hm.put("t","-"); hm.put("u","..-"); hm.put("v","...-"); hm.put("w",".--"); hm.put("x","-..-"); hm.put("y","-.--"); hm.put("z","--.."); for (String key : hm.keySet()) { } } 

    1 answer 1

    We run in a cycle by the entered word, and then in the internal cycle we run by letters, if they match, we output.

     for (char letter : User.toCharArray()) { for (String key : hm.keySet()) { if (letter == key.charAt(0)) { System.out.print(hm.get(key)); System.out.print(" "); } } } 

    https://ideone.com/KJECCQ

    In general, I would recommend making at least Map<Character, String> , not Map<String, String> , so that you don’t have to do key.charAt(0) in the loop (in fact, of course, not only for this :))), and just compare the letters .... Because your key is a symbol, not a string. Then you need to immediately announce it.

    Enchantment Example:

     for (char letter : User.toCharArray()) { for (char key : hm.keySet()) { if (letter == key) { System.out.print(hm.get(key)); System.out.print(" "); } } } 

    https://ideone.com/gah6S9

    • Thanks for the advice: Map <char, String>, but it does not work. Just underlined in red. - Miron Fisenko
    • Because it is necessary to enter a non-primitive type .. Ie Character .... that is, Map<Character, String> .... and the data will be hm.put('a', ".-"); hm.put('b', "-..."); hm.put('a', ".-"); hm.put('b', "-..."); and so on ... that is, single quotes already - Alexey Shimansky
    • Thank! To fill characters. - Miron Fisenko
    • An example for charms led in response too - Alexey Shimansky