0

I tried to add elements to the array,but when I tried to, it showed array is null. I was adding an integer to the array from first element, but still got the problem.Can anyone advise?

class unorderedArray
{
    public int[] itemArray=null ;
    private int numElements=0;
    private int maxElements=0;
    public unorderedArray(int max)
    {
        maxElements = max;
       int[] itemArray=new int[maxElements]  ;
    }
    public int[] getItemArray()
    {
        return itemArray;
    }
    public bool addLast(int item)
    {
        if (numElements < maxElements)
        {
            itemArray[numElements] = item;
            numElements++;

        }

        return true;
    }
}


    class Program
{
    static void Main(string[] args)
    {
        unorderedArray aa = new unorderedArray(60);
        aa.addLast (4);
        aa.addLast(5);
        aa.addLast(6);
        aa.addLast(8);
        aa.addLast(90);
        aa.addLast(12);
        aa.addLast(77);
        aa.printList();
        Console.ReadKey();

    }
}

enter image description here

David Shi
  • 69
  • 2
  • 13

2 Answers2

0
public int[] itemArray=null ; //   <============== THIS

public unorderedArray(int max)
{
    maxElements = max;
   int[] itemArray=new int[maxElements]  ; // <=== AND THIS ...
}

... itemArray are not the same.

If you write int[] itemArray ... you are declaring a local variable that hides the class field.

Just remove the "int[]" from "int[] itemArray..." inside the constructor.

Unrelated: Please stick to the convention to name classes in CamalCase. => "UnorderedArray"

Fildor
  • 14,510
  • 4
  • 35
  • 67
0

You are redeclaring the array thereby making it local which should not be so This

public unorderedArray(int max) {
     maxElements = max; 
     int[] itemArray=new int[maxElements] ;
} 

Should be

 public unorderedArray(int max) {
     maxElements = max; 
     itemArray=new int[maxElements] ;
} 
preciousbetine
  • 2,959
  • 3
  • 13
  • 29