java - Stack Implementation Null Pointer Exception -


this question has answer here:

this program stack implementation using linked list. keep getting java.lang.nullpointerexception @ line number 31, i.e. pop function. why happening , how can correct it?

import java.io.file; import java.io.filenotfoundexception; import java.util.scanner;   public class stackimplementtionlinkedlist  {     private node first= null;      private class node     {         string item;         node next;     }      public boolean isempty()     {         return first==null;     }      public void push(string item)     {         node old= first;         first= new node();         first.item= item;         first.next= old;     }     public string pop()     {         string item= first.item;         first= first.next;         return item;     }     public void printstack()     {         while(first!=null)         {   system.out.println(first.item);             first= first.next;         }     }      public static void main(string[] args) throws filenotfoundexception     {         stackimplementtionlinkedlist stack= new stackimplementtionlinkedlist();         string filename= "myfile.txt";         file textfile= new file(filename);         scanner input= new scanner(textfile);         while(input.hasnextline())         {             string line= input.nextline();             stack.push(line);         }         input.close();         stack.printstack();         string popped= stack.pop();         system.out.println(popped+ " popped item.");         popped= stack.pop();         system.out.println(popped+ " popped item.");         stack.printstack();     } } 

notice after calling method printstack() first null

i make copy , iterate.

public void printstack() {     node copy = first;     while(copy!=null)     {            system.out.println(copy.item);         copy = copy.next;     } } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -