Reputation: 3
A NullPointerException happens and I don't know why.
import java.util.*;
public class One {
//first class with me handling stacks
Stack<String> s = new Stack<String>();
String[] stacks = null;;
public One(){
s.push("one");
s.push("two");
s.push("three");
s.push("four");
s.push("five");
s.push("six");
add();
}
public void add(){
for (int i=0;i<s.capacity();i++){
String temp = (String) s.pop(); //this is the part that gives me a NullPointerException
System.out.println(temp);
}
}
public static void main(String[] args){
One obj1 = new One();
}
}
Upvotes: 0
Views: 57
Reputation: 2404
Use size instead of capacity.
Below is the section which you need to modify
public void add(){
for (int i=0;i<s.size();i++){
String temp = (String) s.pop(); //here
System.out.println(temp);
}
}
Also, I think you don't need that cast there -
String temp = s.pop(); //should do
Upvotes: 0