Java Stack.push() returns NullPointerException
Go to solution
Solved by Pinguinsan,
Any time you use a reference type in Java for a class member , it will be null until it has been assigned using the new keyword. You must first initialize it, preferably in the constructor for your class.
import java.util.EmptyStackException; import java.lang.Math; import java.util.Stack; public class RPNCalc { Stack<Double> st; double first; double second; //Constructor for RPNCalc, called anytime a new RPNCalc is created with the new keyword, as you do in //the first line of Main public RPNCalc() { this.st = new Stack<Double>(); //Initialize member variable st to a new Stack<Double>() so it can be used } public static void main(String[] args) { RPNCalc test = new RPNCalc(); //Calls RPNCalc constructor test.push(1.0); System.out.println(test.getSize()); System.out.println(test.pop()); } // place the number/argument on the top of the stack void push(double number) { st.push(number); } // get size of stack int getSize() { Stack<Double> tmpStack = new Stack(); // create new temorary stack tmpStack = this.st; // set tmpStack to st int counter = 0; // iterate through the tmpStack until it is empty, and count elements while (true) { try { tmpStack.pop(); } catch (EmptyStackException e) { break; // break if stack is empty } catch (NullPointerException e) { break; // break if the stack is empty } counter++; // count the elements in the stack } return counter; } }
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now