堆叠添加但不单独

时间:2018-01-31 23:42:59

标签: java stack

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);
  }
}

Stack可以提供类似[[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]

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

1 个答案:

答案 0 :(得分:0)

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

相关问题