堆栈已添加,但不是单独添加的


public class New1 {
  public static void main(String[] args) {
      int x = 0;
      int cost = 1;
      int y = 0;
      int g = 0;
      Stack<Stack<Integer>> stack = new Stack<>();//stackk within stack
      Stack<Integer> s1 = new Stack<>();
      s1.push(x);
      s1.push(y);
      s1.push(g);
      stack.push(s1);
      System.out.println("before function calling"+stack);
      int [] b=fun1(x,y,g,cost);//Here is error
      System.out.println(x);//But x doesn't hold this value it is zero          
      System.out.println(Arrays.toString(b));//print the value that return by a[]
      s1.push(x);
      s1.push(y);
      s1.push(g);
      System.out.println("After function calling"+stack);
  }
  public static int[] fun1(int d, int b, int c,int f) {
      int [] a=new int[3];
      for (int i = 0; i < 1; i++) {
          int x2=1,y2=1,g2=1;
          d = x2 + f;
          b = y2 + f;
          c = g2 + f;
          a[0]=d;
          a[1]=b;
          a[2]=c;
      }//want to push the updated value into the stack s1.
      return (a);
  }
}

堆栈可以像[[0,0,0][2,2,2]]那样给出输出,但没有。此外,每当 s1 值更新时,它都会像个人一样推送主堆栈。表示如果我的 for 循环运行第二次,值将为 [3,3,3]。它像[[0,0,0],[2,2,2][3,3,3]]一样保留在同一个主堆栈上。但是所有都像[0,0,0,2,2,2,3,3,3]一样合并.

没有产生所需的输出,找不到错误。

你的问题不清楚。您的代码目前只是将 x,y,g 添加到堆栈两次,因此输出为 [0,0,0,0,0,0]。您永远不会使用函数 f 返回的新值。如果将函数 f 返回的值推送到新堆栈,然后将该堆栈添加到名为"stack"的堆栈中,则将获得所需的输出 [[0,0,0][2,2,2]]。 如果我理解正确,请发表评论。

最新更新