Java 在堆栈中弹出元素,直到某个元素
我有这样一个代码:Java 在堆栈中弹出元素,直到某个元素,java,stack,Java,Stack,我有这样一个代码: public static void main(String[] args) throws Exception { String popElement ; Stack<String> stack = new Stack(); stack.push( "new" ); stack.push( "new" ); stack.push( "new1" ); stack.push( "new2" ); if(! stack.em
public static void main(String[] args) throws Exception {
String popElement ;
Stack<String> stack = new Stack();
stack.push( "new" );
stack.push( "new" );
stack.push( "new1" );
stack.push( "new2" );
if(! stack.empty() )
{
do
{
popElement = stack.pop();
System.out.println( "pop element "+popElement );
}while (popElement.equals( "new" ));
}
System.out.println( "STACK :"+stack );
publicstaticvoidmain(字符串[]args)引发异常{
字符串元素;
堆栈=新堆栈();
堆叠。推送(“新”);
堆叠。推送(“新”);
堆栈推送(“new1”);
堆栈推送(“new2”);
如果(!stack.empty())
{
做
{
popElement=stack.pop();
System.out.println(“pop元素”+pop元素);
}而(popElement.equals(“新”));
}
System.out.println(“STACK:+STACK”);
我想弹出堆栈直到新,我需要堆栈输出为[new,new]
。但是我的代码只弹出new2
,它显示输出为[new,new1
。换句话说,我只需要[new,new]]
,
弹出的元素太多。
要检查下一个元素是否为“新元素”,
在不实际移除该元素的情况下,
您需要使用peek()
而不是pop()
而且,
为了避免在所有元素都是“新”时程序崩溃,
您需要反复检查堆栈是否为空
while (!stack.empty() && !stack.peek().equals("new")) {
System.out.println("pop element " + stack.pop());
}
System.out.println("STACK :" + stack);