I was trying to solve this problem in UVa, but I get a NullPointerException at line 16 (at the for loop). I’m fairly new in Java and I don’t know why is it happening. The output looks okay, but I would like to know why it is returning a NPE. Here’s my code:
import java.io.*;
class Crypt {
public static void main(String[] args) throws IOException {
String line = "";
String buffer = "";
char[][] hash = {{'a', 'p'}, {'b', 'l'}, {'c', 'o'}, {'d', 'k'}, {'e', 'm'},
{'f', 'i'}, {'g', 'j'}, {'h', 'n'}, {'i', 'u'}, {'j', 'h'},
{'k', 'b'}, {'l', 'y'}, {'m', 'g'}, {'n', 'v'}, {'o', 't'},
{'p', 'f'}, {'q', 'c'}, {'r', 'r'}, {'s', 'd'}, {'t', 'x'},
{'u', 'e'}, {'v', 's'}, {'w', 'z'}, {'x', 'a'}, {'y', 'q'},
{'z', 'w'}};
BufferedReader f = new BufferedReader(new FileReader("crypt.in"));
while(f != null) {
line = f.readLine();
buffer = "";
for(int i = 0; i < line.length(); i++) {
if(line.charAt(i) == ' ') {
buffer += ' ';
} else {
for(int j = 0; j < hash.length; j++) {
if(line.charAt(i) == hash[j][1]) {
buffer += hash[j][0];
}
}
}
}
System.out.println(buffer);
}
}
}
I’m looking forward for a good explanation. Thanks.
Your
linevariable seems to benull. Usef.ready()to check if there are any more lines remaining in the file.f != nullis incorrect because it merely tests if theBufferedReaderobjectfexists, so it will never be false in this case.