0

why is it not working?

this code is removing the last element in a Stack. i need to remove the last element and then return the element that i removed. how can i make it that it will remove it(i did it well) and then return the element that i removed (struggeling with it)... code: import java.util.*; public class Main { public static void main(String[] args) { Stack<Integer> myStack = new Stack<Integer>(); myStack.add(0); myStack.add(1); myStack.add(2); myStack.add(3); myStack.add(4); System.out.println(myStack); lastAndRemove(myStack); System.out.println(myStack); } public static void lastAndRemove(Stack<Integer> s){ s.remove(s.lastElement()); } }

11th Jul 2020, 8:27 PM
Yahel
Yahel - avatar
3 Answers
+ 3
If you're trying to both get and remove the last element use the Stack.pop() method. Using remove in this fashion may result in a bug when you have multiple elements in the stack with the same value as remove() will remove the first that it finds. You don't need to create a method that already exists. https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html
11th Jul 2020, 10:42 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
You can store the element before removing in a variable and then remove it from the stack and at last return the value stored in the variable. This might be helpful https://code.sololearn.com/cbYQB7H1BR3p/?ref=app
11th Jul 2020, 8:45 PM
XXX
XXX - avatar
0
XXX thanks!
11th Jul 2020, 9:19 PM
Yahel
Yahel - avatar