java - weird Null Pointer Exception -


i trying implement array using 2 stacks named stack , buffer. stack filled random values, myarrayi interface contains 2 functions: getitemat(int index) , setitemat(int index, int item). , implemented in mystackarray class. whenever run program null exception error, have tried trace cause till found stack isn't filled initial data - maybe. whenever try access stack or buffer nullpointerexception error. , when try print elements inside array stack, still silly npe error !!!

public class mystackarray implements myarrayi {     private int[] buffer;     private int[] stack;     private int maxsize;      public mystackarray(int s){         maxsize = s;         int[] buffer = new int [maxsize];         int[] stack = new int [maxsize];          for(int i=0; i<maxsize; i++)             stack[i]=i;    // initiallizing array random values.     }      public void print(){              // tried check contents of stack array.          for(int i=0; i<maxsize; i++)           system.out.println(stack[i]); // causes null pointer exception. ??!         //system.out.println(stack[0]); // still causes npe !!      }      public void setitemat(int index, int item){         int i;         int j;              for(i=0, j=maxsize-1 ; i<maxsize && j>=0 ; i++, j--){                 if(j == index)                     break;                 buffer[i] = stack[j];  //causes null.pointerexception            }            stack[j] = item;        }      public int getitemat(int index){         int i;         int j;              for(i=0, j=maxsize-1 ; i<maxsize && j>=0; i++, j--){                 if(j==index)                     break;                 buffer[i] = stack[j];   // causes npe            }            return stack[j];       }      public static void main(string[] args) {        mystackarray x = new mystackarray(3);       //x.setitemat(0,4);  // causes npe       //x.getitemat(1);    // causes npe     x.print();             // causes npe     } } 

int[] stack = new int [maxsize]; 

here, creating new variable called stack - not same this.stack. instead want:

stack = new int[maxsize];  // i.e. initialize this.stack, not variable 

when left uninitialized, this.stack remains null , receive npe when try access it.

p.s. you're doing same thing buffer.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -