请原谅我糟糕的编程能力。我正在尝试编写一种将英语转换为莫尔斯代码的方法。如您所见,我使用hashmap存储等效项,然后将其转换并将莫尔斯代码存储到变量' result'中。我担心的是我无法返回变量'结果'循环之外。如果我返回' 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;
}
答案 0 :(得分:0)
试试这样:
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();
}