我寫的英語翻譯莫爾斯,每次HashMap中,當我運行出現錯誤:NullPointerException異常索引與字符
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;
}
錯誤。下面是設置了我的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的潛在原因。因此,首先**解析**這些語句,以瞭解您使用的哪些對象實際上是空的。 – GhostCat
你能告訴我們哪一行代碼和'translate'開始? – Addison
並提示代碼質量:構造函數**從不**做「真正的工作」。使用它們來創建新對象,而不是打開文件,閱讀內容並翻譯它。相反:你在班上放了很多小方法來完成所有這些事情。獎勵包括:如果你這樣做,突然之間,你將能夠**測試**所有這些小方法......一個接一個,具有非常明確的範圍和更少的努力。長話短說:閱讀有關https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)...特別是** SRP **。 – GhostCat