Search code examples
javainputhashmapjava.util.scannermorse-code

Getting values from HashMap according to user input / morse code generator


I am trying to create a Java program that takes a users string input and translates it into morse code. I am attempting to store each letter of the alphabet in a hashMap with its corresponding morse code & my goal is to be able to get the value (morse code) when the key(regular letter) is read from the input. Ive attempted something below but it keeps printing null when I test it out. I am fairly new to java and can't seem to figure out how to do this.

import java.util.HashMap;
import java.util.Scanner;

public class Alphabet{

public static void main(String args[]) {

    Scanner sc = new Scanner(System.in);

    HashMap morsecode = new HashMap();
    morsecode.put("a",",-");
    morsecode.put("b","-...");
    //will add other letters later

    System.out.println("please enter an english sentence:");
    String val = (String)morsecode.get(sc.nextLine());
    System.out.println(val);        


}
}

Solution

  • As I said in my initial comment, please don't use raw types. Here your Map should probably be of Character, String because that is why you can't currently map multiple characters in a line to single characters in your Map. Basically, I would do it something like

    Scanner sc = new Scanner(System.in);
    
    Map<Character, String> morsecode = new HashMap<>();
    morsecode.put('a', ",-");
    morsecode.put('b', "-...");
    // will add other letters later
    
    System.out.println("please enter an english sentence:");
    String line = sc.nextLine();
    for (char ch : line.toLowerCase().toCharArray()) {
        System.out.print(morsecode.get(ch) + " ");
    }
    System.out.println();
    

    But you could also do

    Scanner sc = new Scanner(System.in);
    
    Map<String, String> morsecode = new HashMap<>();
    morsecode.put("a", ",-");
    morsecode.put("b", "-...");
    // will add other letters later
    
    System.out.println("please enter an english sentence:");
    String line = sc.nextLine();
    for (char ch : line.toLowerCase().toCharArray()) {
        System.out.print(morsecode.get(Character.toString(ch)) + " ");
    }
    System.out.println();
    

    or any other method of iterating single characters from the user's input.