Search code examples
methodshashmapmorse-code

Morse code conversion on how to return a method


Please pardon me for my weak porgramming ability. I'm trying to write a method converting english to morse code. As you can see, I use hashmap to store the equivalant and then convert it and stored the morse code into the variable 'result'. My concern is I can't return the variable 'result' outside of the loop. If i return 'dataInput', isn't it just returning the original input? How can I return the correct result?

public static String morseCode(String dataInput)
{
     Map<String, String> morseCode = new HashMap<String, String>();
     morseCode.put("a", ".-");            
     morseCode.put("b", "-...");
     morseCode.put("c", "-.-.");


        for (int i = 0; i<dataInput.length(); i++)
        {
            String result = (String)morseCode.get(dataInput.charAt(i)+"");
            //convert input data into morse code

        }

        return dataInput;        
}

Solution

  • Try like this:

      import java.lang.StringBuffer; //at the top
    
      Map morseCode = new HashMap(); 
      morseCode.put("a", ".-");
      morseCode.put("b", "-..."); 
      morseCode.put("c", "-.-."); 
      StringBuffer buff = new StringBuffer();
    
      for (int i = 0; i<dataInput.length(); i++)
        {
            String result = (String)morseCode.get(dataInput.charAt(i));
            //convert input data into morse code
            buff.append(result+" ");
        }
       return buff.toString();
     }