简体   繁体   中英

Creating stack of stack in Java

I want to create a stack of Integer stack. So that I can push a new integer stack in main stack.

How to create it? I have done the following code for that:

import java.util.*;
import java.io.*;

public class Containers{
    static Stack<Integer> subStack = new Stack<Integer>();
    static Stack<subStack> main  = new Stack<subStack>();
   public static int addToStatck(char cont){
       //for(int j=0;j<)
        return 0;
    }
    public static void main(){
        Scanner sc = new Scanner(System.in);
        String container = sc.next();
        Stack sub = new Stack();
        sub.push(container.charAt(0));
        main.push(sub);
        int ans = 0;
        for(int i=0;i<container.length();++i){
            ans+=addToStatck(container.charAt(i));
        }

    }

}

it Shows me the following output: 在此输入图像描述

There is no subStack type (unless you create such type).

The type of main should be:

static Stack<Stack<Integer>> main = new Stack<>();

And there doesn't seem to be any use to your

static Stack<Integer> subStack = new Stack<Integer>();

variable.

Besides,

Stack sub = new Stack();

should be

Stack<Integer> sub = new Stack<>();

To summarize:

public class Containers{
    static Stack<Stack<Integer>> main = new Stack<>();
    public static int addToStatck(char cont){
        //for(int j=0;j<)
        return 0;
    }
    public static void main(){
        Scanner sc = new Scanner(System.in);
        String container = sc.next();
        Stack<Integer> sub = new Stack<>();
        sub.push(Integer.valueOf (container.charAt(0)));
        main.push(sub);
        int ans = 0;
        for(int i=0;i<container.length();++i){
            ans+=addToStatck(container.charAt(i));
        }   
    }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM