我尝试在Java中实现Morse代码转换器,使用尽可能少的代码,但在我的程序中我得到一个错误,导致hashmap超出边界。是否可以指定地图的大小等于字符串的长度,我输入?但不少于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]+" ");
}
}
答案 0 :(得分:2)
您只需要查看当前字母是否包含在地图中,如果是,那么您可以在单词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
这将转换地图知道的所有字母,因为它不会改变。
答案 1 :(得分:1)
if(checker.equals(words.keySet().toArray()[i]))
{
System.out.print(words.values().toArray()[i]+" ");
}
将其更改为:
if(words.get(checker) != null)
System.out.print(words.get(checker) + " ");