0

请原谅我的编程能力较弱。我正在尝试编写一种将英语转换为莫尔斯电码的方法。如您所见,我使用 hashmap 存储等价物,然后将其转换并将莫尔斯电码存储到变量“结果”中。我担心的是我无法在循环之外返回变量“结果”。如果我返回'dataInput',它不只是返回原始输入吗?我怎样才能返回正确的结果?

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

1 回答 1

0

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();
 }
于 2015-03-31T06:44:45.933 回答