0

I'm having some trouble understanding why the Scanner is not picking up the "(" character when it is clearly there. When I tried to save my program, there was a pop-up that said that some of the characters couldn't be saved in the proper encoding. (I'm using Eclipse, and it uses Cp1252 encoding if that would be of any help) I changed it to UTF-8, and now I'm having these issues.

String input = "a 0 ( b 4 ( * 100 b 6 ) w 9 ( x 3 y 5 ( * 2 z 3 ) ) )";
LinkedStack<TreeNode<String>> stack = new LinkedStack<TreeNode<String>>();
Scanner in = new Scanner(input);
    while (in.hasNext()) {
        String temp = in.next();
        System.out.println("Here's a temp:" + temp);
        if (temp == "(") {
            System.out.println("Continuing.");
            continue;
        }
        else if (temp == ")") {
            System.out.println("Closed Paren.");
            TreeNode<String> leftChild = stack.pop();
            TreeNode<String> rightChild = stack.pop();
            TreeNode<String> parent = stack.pop();
            parent.setLeft(leftChild);
            parent.setRight(rightChild);
            stack.push(parent);
        }
        else {
            System.out.println("Hit the else block.");
            String label = temp;
            String distanceString = in.next();
            double distance = Double.parseDouble(distanceString);
            System.out.println("Here is the distance of this node: " +distance);
            stack.push(new TreeNode<String>(label, null, null, distance));
        }
    }   
Kennah
  • 1

1 Answers1

1

When using == like that, the two string are checked to see if they have the same reference, which in this case will return false.

You should use temp.equals("(") and temp.equals(")") and so on.

Comparing the strings with equals method checks their values, which will be true here.

Robo Mop
  • 3,485
  • 1
  • 10
  • 23
  • And that's the case because it is a String, which is technically an object, right? – Kennah Dec 09 '17 at 17:19
  • Yes. But the address of the object will be different from the address of the string ")", despite their values being the same. – Robo Mop Dec 09 '17 at 17:20