简体   繁体   English

为什么即使我将某些东西推入堆栈,堆栈仍是空的?

[英]Why is it saying stack is empty even though I push something into it?

For some reason when I call the stack1.empty() or stack1.isEmpty(), it returns true even though I pushed something into the stack? 由于某种原因,当我调用stack1.empty()或stack1.isEmpty()时,即使我将某些内容推入堆栈,它也会返回true? Here is the method I use to push something into the stack... 这是我用来将某些东西推入堆栈的方法...

//Case B:
     else if(currentChar == '('){
         Character charObj = Character.valueOf('(');
         stack1.push(charObj);
         System.out.println("Case B");
     }

Basically it iterates through each character in a string, and does one of the cases that I coded. 基本上,它会遍历字符串中的每个字符,并执行我编码的情况之一。 In this case, the character is a '(', so I have it pushed into the stack. 在这种情况下,字符为'(',因此我将其压入堆栈。

Now, the next character in the string is a letter, so this case is called: 现在,字符串中的下一个字符是字母,因此这种情况称为:

//Case A:
     if(currentChar != '+' && currentChar != '-' && currentChar != '*' && currentChar != '/' && currentChar != '(' && currentChar != ')' ){
         postfixString += currentChar;
         System.out.println("Case A");
     }

That method works fine. 该方法工作正常。 Now the next part goes wrong for some reason. 现在,下一部分由于某种原因而出错。 The next thing in the string is a *. 字符串中的下一个内容是*。 SO, it's supposed to run a certain case that I coded, but instead it runs a different case....Here is the case that it runs: 因此,它应该运行我编写的某种情况,但是它运行的是另一种情况。...这是它运行的情况:

//Case C:
     else if(stack1.empty() && currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/'){
         stack1.push(currentChar);
         System.out.println("Case C");
     }

As you can see, the only way to run this case is if the stack is empty, but it's not empty! 如您所见,运行这种情况的唯一方法是堆栈空,但不为空! I pushed something into the stack... I don't understand why it keeps running this case even though the stack is not empty. 我将某些东西推入堆栈...即使堆栈不为空,我也不明白为什么它会继续运行这种情况。

I want it to run this case instead: 我希望它运行这种情况:

     //Case D: If character is an operator, it goes into a loop checking if topstack is higher precedence to the current character
     // If it is, the stack pops onto the end of the postfix string. If it isn't, the stack pushes the current scanned character.
     // It then breaks out of the loop
     else if(currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/' && !stack1.isEmpty()){
         char topStack = stack1.peek();

        while(!stack1.isEmpty()){
            if(precedence(topStack, currentChar)){
                postfixString += stack1.pop();
            }
            else{
                stack1.push(currentChar);
                break;
            }

            System.out.println("Case D");

        }



     }

I mean it should run case D, but instead it runs case C. Why is it doing this? 我的意思是应该在情况D下运行,而在情况C下运行。为什么要这样做?

EDIT: 编辑:

Here's the entire class: 这是整个课程:

import java.util.Stack;

public class InfixToPostfixConverter
{
//**********************************************************************
//The precedence method determines the precedence between two operators.
//If the first operator is of higher or equal precedence than the second
//operator, it returns the value true, otherwise it returns false.
//***********************************************************************
   public static boolean precedence(char topStack, char currentChar)
   {
   if(topStack == currentChar){
       return true;
   }

   // If topStack is division or multiplication, it will always have precedence no matter what
   if(topStack == '/' || topStack == '*'){
       return true;
   }
   // If topStack is addition or subtraction...
   else if(topStack == '+' || topStack == '-'){
       if(currentChar == '+' || currentChar == '-'){
           return true;
       }
       else if(currentChar == '*' || currentChar == '/'){
           return false;
       }
   }

   return false;
   }

//*************************************************************************
//The static convertToPostfix method will convert the infixString
//into the corresponding postfix string. Check the algorithm on
//assignment #11's description page. Mark each case clearly inside the code
//*************************************************************************
   public static String convertToPostfix(String infixString)
   {
  //initialize the resulting postfix string
  String postfixString = "";

  //initialize the stack
  Stack<Character> stack1 = new Stack<Character>();

 //Obtain the character at index i in the string
  for (int i=0; i < infixString.length(); i++)
  {
     char currentChar = infixString.charAt(i);

    //Case A:
     if(currentChar != '+' && currentChar != '-' && currentChar != '*' && currentChar != '/' && currentChar != '(' && currentChar != ')' ){
         postfixString += currentChar;
         System.out.println("Case A");
     }

    //Case B:
     else if(currentChar == '('){
         stack1.push(currentChar);
         System.out.println("Case B");
     }

     else if(currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/'){
         //Case C
         if(stack1.isEmpty()){
             stack1.push(currentChar);
             System.out.println("Case C");
         }
         //Case D
         else{
             char topStack = stack1.peek();

             while(!stack1.isEmpty()){
                if(precedence(topStack, currentChar)){
                    postfixString += stack1.pop();
                }
                else{
                    stack1.push(currentChar);
                    break;
                }

                System.out.println("Case D");

            }
         }
     }
    //Case E:
     else if(currentChar == ')' && !stack1.isEmpty()){
         while(!stack1.isEmpty() && stack1.peek() != '('){
             postfixString += stack1.pop();
             System.out.println("Case E");
         }
         if(!stack1.isEmpty() && stack1.peek() == '('){
             stack1.pop();
         }
     }


  } //end of for loop


    //Case F:
  if(!stack1.isEmpty() && stack1.peek() == '('){
      return "No matching close parenthesis error.";
  }
  else if(!stack1.isEmpty() && stack1.peek() != '('){
      while(!stack1.isEmpty() && stack1.peek() != '('){
          postfixString += stack1.pop();
      }
  }

  System.out.println("Case F");
  return postfixString;


}//end of convertToPostfix method

}//end of the InfixToPostfixConverter class

The && operator has a higher precedence than || &&运算符的优先级高于|| , so in this statement: ,因此在此语句中:

else if(stack1.empty() && currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/'){

The above is equivalent to: 以上等同于:

else if( ( stack1.empty() && currentChar == '+' ) || currentChar == '-' || currentChar == '*' || currentChar == '/'){

For a simpler example: 举一个简单的例子:

if (a && b || c)

is equivalent to 相当于

if ( (a && b) || c )

When in doubt, add parens to make the order of operations explicit so that you (and other programmers reading your code) are clear on your intention. 如有疑问,请添加括号以使操作顺序明确,以便您(和其他阅读代码的程序员)清楚您的意图。

Explanation 说明

What this means for your overall question is, your stack1 is probably not empty. 这对于您的总体问题意味着什么,您的stack1可能不是空的。 In the else if I've quoted above, stack1.empty() && currentChar == '+' would both have to be true. else if我在上面引用过, stack1.empty() && currentChar == '+'都必须为true。 Since that isn't the case, the next terms are evaluated until it gets to currentChar == '*' , which is true, so it runs Case C. 由于不是这种情况,因此将评估下一项,直到它到达currentChar == '*'为止,这正确的,因此它将运行案例C。

Your Case D will never be true, because Case C already checks the same characters. 您的情况D永远不会正确,因为情况C已经检查了相同的字符。 Case D will not be reached. 情况D将无法达成。

Assuming Case C is supposed to mean both "stack1 is empty" AND "currentChar is one of +, -, *, or /", then you would need to write it as such: 假设案例C表示“ stack1为空”和“ currentChar是+,-,*或/之一”,那么您需要这样写:

else if (stack1.empty() && (currentChar == '+' || ...)) {

But since you are checking for the same characters every time, I would personally use a multi-level if statement: 但是由于您每次都要检查相同的字符,因此我个人会使用多级if语句:

else if (currentChar == '+' || currentChar == '-' || ...) {
    if (stack1.empty()) {
    // Case C

    } else {
    // Case D

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使堆栈没有对象,堆栈也不会返回空 - Stack not returning empty even though it has no objects 为什么即使我将元素推入堆栈,堆栈仍然是空的 - Why is stack still empty even when I pushed an element into it 为什么即使我在请求期间向其中添加了元素,此代码也会显示一个空数组列表? - why this code shows an empty array list even though i added elements to it during request? 为什么单元格值即使包含内容也作为空字符串返回? - Why is a cell value returned as an empty string even though it has content? 即使输入了文本,为什么Android EditText也显示为空? - Why does Android EditText shows empty even though there is text entered? 为什么即使 Firebase 数据快照包含子项,我的 ArrayList 也是空的 - why is my ArrayList empty even though firebase datasnapshot contains children 收到错误提示 java 中的堆栈为空 - Receiving a error saying that stack is empty in java leetcode 即使它为空,也是必需的linkedInDistributionTarget - linkedInDistributionTarget is required even though it is empty 为什么即使使用锁,也会出现ConcurrentModificationException? - Why I get ConcurrentModificationException even though I am using locks? 为什么我不能在这里使用.invokeExact(),即使MethodType没问题呢? - Why can't I .invokeExact() here, even though the MethodType is OK?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM