How do I make a loop to put a stack into a string[]?

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

Answers (2)

Tirath
Tirath

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

folkol
folkol

Reputation: 4883

Use size instead of capacity, if you want to see how many items are in the stack right now.

You can pop all items from a stack like this:

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

Upvotes: 2

Related Questions