【发布时间】:2016-07-08 14:07:58
【问题描述】:
我正在编写一个英语到摩尔斯翻译器,每次运行时都会出现错误:
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 数组充满了短语的小写字符,但由于某种原因它仍然会产生错误。任何关于我做错了什么的建议将不胜感激。
【问题讨论】:
-
提示:该行包含 3 个可能引发 NPE 的潜在原因。因此,首先剖析这些语句,以了解您使用的哪些对象实际上是空的。
-
您能告诉我们
Code和translate从哪一行开始吗? -
并提示代码质量:构造函数从不做“真正的工作”。使用它们来创建新对象,而不是打开文件、读取内容和翻译。相反:你在你的类上放了许多小方法来做所有这些事情。奖励包括:如果您这样做,突然之间,您将能够测试所有这些小方法......一个一个,范围非常明确,而且工作量少得多。长话短说:阅读en.wikipedia.org/wiki/SOLID_(object-oriented_design) ...,尤其是SRP。
-
System.out.println(morse + " " + map + " " + phraseList[x] + " " + map.get(phraseList[x]);哪个为空?
标签: java string nullpointerexception hashmap character