I've written a small program where I have a two dimensional array with String names. In a nested for loop I check for the first character in each element of the array. If the first character is 'A' || 'E' || 'I' || 'O' || 'U', I write that element into a file with FileWriter. However, every time I try to compile the program I get NullPointerException. This is the code:
FileWriter fw = new FileWriter("imena.txt");
String polje[][] = new String[5][5];
polje[0][0] = "Janez";
polje[0][1] = "Tine";
polje[0][2] = "Miha";
polje[0][3] = "Klemen";
polje[0][4] = "Jure";
polje[1][0] = "Tone";
polje[1][1] = "Andrej";
polje[1][2] = "Janko";
polje[1][3] = "Nejc";
polje[1][4] = "Erik";
for(int i = 0; i < polje.length; i++) {
for(int j = 0; j < polje[0].length; j++) {
if(polje[i][j].charAt(0) == 'A') {
fw.write(polje[i][j] + '\n');
}
}
}
If I change the if to if(polje[1][1].charAt(0) == 'A')
it runs perfectly fine, but I want to iterate over all of the elements in the array. Any help would be most appreciated.
As it turns out, I forgot to initialize all of the elements in my array. I can't believe I couldn't see the problem myself. :)
Thanks for the help, everyone! ;)
You've only initialized as far as polje[1][...]
. So when i
is 2 (and j
is anything), polje[i][j]
will be null... and when you dereference it by calling charAt(0)
, you'll get the exception.
Note that this sort of error can be avoided using List
instead of arrays, where the size grows dynamically. You could even mix the two:
List<String[]> polje = new ArrayList<>();
polje.add(new String[] { "Janez", "Tine", ... };
polje.add(new String[] { "Tone", "Andrej", ... };
for (String[] array : polje) {
for (String item : array) {
// This way you'll handle empty strings, too
if (item.startsWith("A")) {
fw.write(item + '\n');
}
}
}
See more on this question at Stackoverflow