0

My code compiles but it has a java null error.

import java.util.Arrays;

public class Example
{
    private int[] NumberArray;

    public Example()
    {
        int[] NumberArray = new int[4];
    }

    public void setNumberArray()
    {
        NumberArray[0] = 20;
        NumberArray[1] = 15;
        NumberArray[2] = 22;
    }

    public void printnumberArray()
    {
        for(int index=0; index < NumberArray.length; index++)
        {
           System.out.println(NumberArray[index]);
        }
    }
}

Edited by pritaeas: Changed to thread.

2
Contributors
6
Replies
14
Views
2 Years
Discussion Span
Last Post by wids101
0

EXACTLY what code are you executring and EXACTLY what is thet COMPLETE error message?

ps Did you intend that line 9 will create a new "NumberArray" variable? The NumberArray that you initialise in setNumberArray isn't the one declared on line 5!

Edited by JamesCherrill

0

I'm trying to see how the array works and i'm trying to print the array using a for loop. Yes on the "NumberArray variable but don't you have intiazile the array? My error is

java.lang.NullPointerException
    at Example.printnumberArray(Example.java:28)
0

Yes.
YOu have TWO variables"NumberArray", declared on lines 5 and 9.
The one you initialise is declared on line 9, and never used anywhere else.
The one declared on line 5 is the one you (try to) use, but that's not initialised.

0

Your mistake is declaring the same variable name twice. On line 9, just use the one you already have, don't declare a new one.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.