1

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();
            }
        }
2
  • 2
    I thought I was in the wrong section when I saw your code. Where is the C++ in this question? This looks like Java. Commented Oct 28, 2019 at 13:53
  • I'd definitely say it's Java, in fact my answer is based on Java (BufferedReader does not exist in C++, as far as I know) Commented Oct 28, 2019 at 13:59

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this way too, I think the problem here is with the parseInt().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.