-1

I am trying to interpret a string input from the user. I take in a phrase, split it into an array, and compare each value in the array to ")" as a boolean. The problem is it will read the string "( 3 + 5 )", and I know that the array that takes in the string is ["(","3","+","5",")"] and when I print out position 0 and 4 of the array, it returns "(" and ")". I know that these are type string of length 1, however, when I compare the exact same values to the "(" ")" in the code, it returns false.

Any idea what's wrong? Here's my code. The parts that I am having trouble with are the if statements.

    public String buildExpression(String E){
        String[] exprArr=E.split(" ");      
        int len=exprArr.length;
        BTStacker S = new BTStacker();
        String val;
        for (int i=0; i<len; i++){
            val=exprArr[i];
            System.out.println(val);
            if (val=="("){
                System.out.println("2");
            }
            else if(val != ")"){
                BSTree T=new BSTree();
                BSTNode v=new BSTNode(val,null);
                T.addRoot(v);
                S.push(T);
            }
            else{
                BSTree Ty = S.pop();
                BSTree T=S.pop();
                BSTree Tx=S.pop();
                T.attach(T.root(),Tx,Ty);
                S.push(T);
            }

        }
    }

2 Answers2

4

When you compare Strings in Java, you need to use .equals(), not ==, because Strings are Objects.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
4

NEVER compare strings using ==.

Always compare using the equals method.

val.equals("(")

Note that when using "==" to compare string objects, you are not comparing it's values but it's references.

Kuba Spatny
  • 26,618
  • 9
  • 40
  • 63