-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
  • You are not comparing strings, but references to strings. Commented Nov 16, 2013 at 20:22
  • 1
    Does nobody search or read documentations anymore before they ask questions? Commented Nov 16, 2013 at 20:24

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.