我正在编写一个英语到莫尔斯翻译器,每次运行时都会出现错误:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.concat(Unknown Source)
at Code.translate(Code.java:49)
at Code.<init>(Code.java:34)
at Morse.main(Morse.java:8)
我试过调试。这是有问题的函数:
String translate(String phrase, HashMap map) { // line 37
//String to contain the morse code
String morse = "";
//Char array to contain the English phrase
char[] phraseList = new char[(int)phrase.length()];
//Fill the char array
phraseList = phrase.toCharArray();
//Loop through the array and concat the morse string with the value returned from the key
for (int x =0; x < phrase.length(); x++) {
if(phraseList[x] == ' ') {
morse.concat(" ");
} else {
//Here's where the error is produced
morse.concat((String) map.get(phraseList[x]));
}
}
return morse;
}
当代码到达“else”条件时产生错误。这是设置传递给此函数的 HashMap 的构造函数:
HashMap<String,String> codeMap = new HashMap<>();
//Gets passed a string phrase from the main class
public Code(String phrase) throws FileNotFoundException { //line 14
String filePath;
String letter;
String code;
//Creates the object that reads the file location
Scanner fileLocate = new Scanner(System.in);
System.out.println("Enter file path of morse code");
//Object reads file location
filePath = fileLocate.nextLine();
//Create file object
filePath=filePath.replace("\\","/");
File morse = new File(filePath);
//Create scanner object that reads the file
Scanner fileRead = new Scanner(morse);
//Loop to read the file and store the info as a key/value pair in a hashmap
while (fileRead.hasNext()) {
letter = fileRead.next().toLowerCase();
code = fileRead.next();
codeMap.put(letter, code);
}
translate(phrase,codeMap);
}
HashMap
充满了正确的小写值,char
数组充满了短语的小写字符,但由于某种原因它仍然会产生错误.任何关于我做错了什么的建议将不胜感激。
最佳答案
尝试
morse.concat((String) map.get( Character.toString(phraseList[x]) ));
// ^^^^^^^^^^^^^^^^^^^^ added this
您的 map 由 String
索引,但由于类型删除,translate
不知道这一点。您正在使用 char
而不是 String
进行索引。这意味着你得到一个 autoboxed Character
,这将不是您输入的 String
。因此, map 将不包含您期望的条目,并将返回 null
— 空指针异常
。
解释:根据this answer ,hashCode
是HashMap
中的第一个校验。之后,Object.equals()
用于在映射中查找键。两者 String.equals(Character)
和 Character.equals(String)
将返回错误。因此,即使 String("a")
和 Character('a')
的 hashCode
值可能相同,但这两个是不被认为是相等的,所以它们不能作为键互换使用。
关于java - 使用字符索引 HashMap 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38268726/