I'm writing an English to Morse translator and every time I run it an error appears:
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)
I've tried debugging. Here's the function with the problem:
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;
}
The error is produced when the code reaches the "else" condition. Here is the constructor that sets up my HashMap that's passed to this function:
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);
}
The HashMap
is full of the correct, lowercase values and the char
array is full of the lowercase chars of the phrase, but for some reason it still produces the error. Any advice on what I'm doing wrong would be greatly appreciated.