【发布时间】: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]一样合并。
没有产生所需的输出并且找不到错误。
【问题讨论】:
-
一点建议,您应该为变量选择更好的名称。
a、x和x2之类的名称会让人非常困惑,而且速度非常快。 -
您能否编辑您的问题以更清楚地解释您的代码试图做什么?查看输入、预期输出和实际输出的一些清晰示例也会有所帮助。