简体   繁体   中英

How to avoid NullPointException in the BufferReader?

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();
            }
        }

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.

  • If you want to use dynamic sized arrays that will grow automatically whenever you add an item, learn about ArrayLists .

    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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM