Some operation is performed on an array in function fillStackWithArray()
and after the operation the array is pushed into the stack and is repeated again.
But the issue occurs when I try to print the stack. It gives me wrong answer.
Output:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Expected Output:
5 5 5 5 5 4 4 4 4 4 3 3 3 3 3 2 2 2 2 2 1 1 1 1 1
Code:
import java.util.Stack;
public class ArraysOnStack {
public static void main(String[] args) {
int sizeOfArray = 5;
Stack<int[]> stack = fillStackWithArray(5);
printStack(stack);
}
private static void printStack(Stack<int[]> stack) {
while (!stack.empty()) {
int[] arr = stack.pop();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
private static Stack<int[]> fillStackWithArray (int size) {
Stack<int[]> stack = new Stack<>();
int[] arr = new int[size];
// Some Operation that fills Stack with Arrays.
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
arr[j] = size - i;
}
// Pushing the array into stack on which some operation
// is performed.
stack.push(arr);
}
return stack;
}
}
PS: The operation is random to just fill the array. But my question is related to such a situation.