【问题标题】:stack added but not separately堆栈添加但不单独
【发布时间】:2018-01-31 23:42:59
【问题描述】:
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]一样合并。

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

【问题讨论】:

  • 一点建议,您应该为变量选择更好的名称。 axx2 之类的名称会让人非常困惑,而且速度非常快。
  • 您能否编辑您的问题以更清楚地解释您的代码试图做什么?查看输入、预期输出和实际输出的一些清晰示例也会有所帮助。

标签: java stack


【解决方案1】:

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

【讨论】:

  • 是的,你说得对。我不想将函数 fun() 返回的新值推送到新堆栈中。我想将其推送到与前一个堆栈相同的堆栈中。堆栈数据结构中可能吗?如果不是,那么哪种数据结构适合此操作?第二个认为我在程序中使用 return(a) 返回值。然后在我的主函数中调用 fun() 函数。那么我该如何使用它呢?我不清楚。
  • 我无法理解您的用例。如果您在少数情况下给我输入和预期输出,那将是最好的,我将能够最好地为您提供建议。
猜你喜欢
  • 2013-11-28
  • 1970-01-01
  • 2021-06-15
  • 2019-02-09
  • 2016-07-07
  • 2011-11-08
  • 2019-02-05
  • 1970-01-01
  • 2021-10-04
相关资源
最近更新 更多