0

I'm trying to construct my own expressions evaluator based on the Shunting-yard algorithm. I'm having difficulty adding String objects to the stack I have though. My code just skips over these lines every time, even when the condition is met. Any suggestions? I have the operatorStack declared as:

Stack operatorStack = new Stack();

I'm thinking that it has something to do with my if statement. I've tested it with the Eclipse debugger and when the currentChar variable shows as "(" it still skips over the push to the stack.

Here is the excerpt in question:

int count = 0;
String currentChar=new String();

//While loop to test for the conditions stated in the Shunting-yard algorithm.
while (count<=temp.length()) {

    currentChar = temp.substring(count, count+1);
    if(currentChar == "(")
        operatorStack.push(currentChar);

    if(expressionEval(currentChar) instanceof Integer)
        outputQueue.offer((Integer)expressionEval(currentChar));

    if(currentChar == "+" || 
               currentChar == "-" || 
               currentChar == "<" || 
               currentChar == "?") {

        while(operatorStack.peek() == "+" || 
                          operatorStack.peek() == "-" || 
                          operatorStack.peek() == "<" || 
                          operatorStack.peek() == "?") {
            outputQueue.offer((Integer)operatorStack.peek());
            operatorStack.pop();
        }

        operatorStack.push(currentChar);
    }
poussma
  • 7,033
  • 3
  • 43
  • 68
  • NetBeans gives me a warning when I try to compare strings using `==`, doesn't Eclipse, or are you ignoring it? – Bernhard Barker Nov 05 '13 at 14:10
  • You can probably change `String currentChar=new String();` to `String currentChar;`. The `=new String()` doesn't serve any purpose, based on the given excerpt. ... or just declare it where you assign it - `String currentChar = temp.substring(count, count+1);` – Bernhard Barker Nov 05 '13 at 14:19
  • I knew the duplicate of this question even before reading it ..... sad, but true. – Ingo Nov 05 '13 at 14:23

1 Answers1

2

You are comparing Strings using "==" instead of "equals". The comparison condition is never met.

Also you should consider using "char" instead of "String" when taking a peek at single characters, using myString.charAt(count) (for example).

--- this is considering you are trying this in Java.

Christian Kullmann
  • 558
  • 1
  • 7
  • 21