Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在堆栈中弹出元素,直到某个元素_Java_Stack - Fatal编程技术网

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);