Reputation: 319
So I wrote this code to read a file containing numbers, however I get a NullPointerException error, when I try to assign value to the array.
Here is my code:
private static int []a;
public static int i = 0;
public static void main(String[] args) {
// Get a random generated array
// I'll read from file, which contains generated list of numbers.
BufferedReader reader = null;
try {
File file = new File("numbers.txt");
reader = new BufferedReader(new FileReader(file));
for(String line = reader.readLine(); line!= null; line = reader.readLine()){
//I get error here
a[i] = Integer.parseInt(line);
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 1
Views: 50
Reputation: 523
You forgot to initialize the array, to initialize it you can use
private static int []a = new int[100];
Be careful when working with fixed size arrays because, in this particular case, if your file has more than 99 lines, your program will fail. The while loop would try to write out of the array bounds and it would throw an IndexOutOfBounds
exception.
The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want.
It is worth mentioning that normally, when reading from a file, it is better to use a while loop instead of the for loop:
while ((line = r.readLine()) != null) {
a[i] = Integer.parseInt(reader.readLine());
i++;
}
This way the loop will exit when the BufferedReader
reaches the end of the file, as the r.readLine()
method will return null
.
Upvotes: 3