Java 如何创建循环以将堆栈放入字符串[]?
发生了NullPointerException,我不知道为什么Java 如何创建循环以将堆栈放入字符串[]?,java,arrays,string,stack,Java,Arrays,String,Stack,发生了NullPointerException,我不知道为什么 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
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();
}
}
import java.util.*;
公共一级{
//头等舱,我来处理堆栈
堆栈s=新堆栈();
字符串[]堆栈=null;;
公共一号{
s、 推动(“一”);
s、 推(“两”);
s、 推(“三”);
s、 推(“四”);
s、 推(“五”);
s、 推(“六”);
添加();
}
公共无效添加(){
对于(int i=0;i如果您想查看堆栈中现在有多少项,请使用而不是
您可以按如下方式从堆栈中弹出所有项目:
while(!s.isEmpty()) {
System.out.println(s.pop());
}
使用大小而不是容量
下面是您需要修改的部分
public void add(){
for (int i=0;i<s.size();i++){
String temp = (String) s.pop(); //here
System.out.println(temp);
}
}
使用s.size()而不是s.capacity()使用s.size()并告诉我您是否得到了相同的例外情况capacity用于知道在运行时动态分配给堆栈集合的内存
String temp = s.pop(); //should do