I have a project where I need to get an input from the user, convert that to morse code and vice versa.
I have to use a hashmap, and my code looks like this. It's not really working. I'm having trouble understanding how I can print the input I get from the user on the class engToMorse.
I tried to look through other similar questions as well, but I couldn't find anything that could solve my issue.
Edit 1: By changing .toLowerCase to .toUpperCase, it does work, but only for one word. How would i go about making it work for multiple words, like a sentence. Edit2: That was fixed by adding translator.put(' ', " ");. How would I go about converting morse to english now? It is the same idea?
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++;
}
Your hashmap translations have key is upper case and you was transform all character in your "sentence" to lower case. Change it back to upper case when you get the element in hashmap is the easiest way.
while(i<sentence.length()){
System.out.println(translations.get(Character.toUpperCase(sentence.charAt(i))));
i++;
}