我尝试用 Java 实现莫尔斯电码翻译器,使用尽可能少的代码,但在我的程序中出现错误,因为 hashmap 超出了边界。是否可以将 map 的大小指定为等于我输入的字符串的长度?但不只是输出字母字符,不少于 26 个。谢谢
String a = reader.readLine();
Map<String, String> words = new HashMap<>();
words.put("s", "***"); //only two characters still
words.put("o", "---");
for(int i=0; i<a.length(); i++)
{
String checker = Character.toString(a.charAt(i));
if(checker.equals(words.keySet().toArray()[i]))
{
System.out.print(words.values().toArray()[i]+" ");
}
}
最佳答案
你只需要查看当前字母是否包含在映射中,如果是,那么你可以在单词 hashmap 中获取它对应的映射。
String a = reader.nextLine();
Map<String, String> words = new HashMap<>();
words.put("s", "***"); //only two characters still
words.put("o", "---");
String translated = "";
for(int i=0; i<a.length(); i++)
{
String checker = Character.toString(a.charAt(i));
if(words.containsKey(checker))
{
translated += words.get(checker);
}
else{
translated += checker;
}
}
System.out.println("Input: " + a + ", Morse: " + translated);
输出
sos
Input: sos, Morse: ***---***
sor
Input: sor, Morse: ***---r
这将转换 map 知道的所有字母,对于那些不知道的字母,它不会改变。
关于java - java中使用HashMap的摩尔斯电码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41987555/