【问题标题】:How do I make a loop to put a stack into a string[]?如何进行循环以将堆栈放入字符串 []?
【发布时间】:2014-11-14 23:36:24
【问题描述】:

发生 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("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();
    }
}

【问题讨论】:

  • 使用 s.size() 代替 s.capacity()
  • 使用 s.size() 并让我知道您是否遇到相同的异常
  • 容量用于知道运行时动态分配给堆栈集合的内存

标签: java arrays string stack


【解决方案1】:

如果您想查看当前堆栈中有多少项,请使用 size 而不是 capacity

您可以像这样从堆栈中弹出所有项目:

while(!s.isEmpty()) {
    System.out.println(s.pop());
}

【讨论】:

    【解决方案2】:

    使用大小而不是容量。

    下面是需要修改的部分

    public void add(){
        for (int i=0;i<s.size();i++){
            String temp = (String) s.pop();    //here
            System.out.println(temp);
        }
    }
    

    另外,我认为你不需要那个演员 -

    String temp = s.pop();    //should do
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 2021-06-08
      • 2015-05-07
      • 2012-10-15
      相关资源
      最近更新 更多