-2

I have a problem with my Java code:

public static void GetEquation () {
    equation = Main.userInput.replaceAll(" ", "");

    num1 = Double.parseDouble(equation.substring(0, 1));
    operator = equation.substring(1, 2);
    num2 = Double.parseDouble(equation.substring(2, 3));

    if (operator == "+") {
        result = num1 + num2;
    }
    else if (operator == "-") {
        result = num1 - num2;
    }
    else if (operator == "/") {
        result = num1 / num2;
    }
    else if (operator == "*") {
        result = num1 * num2;
    }

    System.out.println(result);
}

I found that it gets rid of the whitespace fine and it assigns the variables fine but when it comes to doing the math and displaying the result it fails. Whatever I typed in, I would get a result of 0. I can't see what is wrong.

zai-turner
  • 75
  • 1
  • 10
  • You should be doing a `.trim()` instead of that replaceAll nonsense, and instead of doing `operator == "*"` you want `operator.contains("*")` or `.matches("*")` – Petro Apr 21 '16 at 00:07

1 Answers1

0

Operator is a String. You have to use .equals() to compare Strings for content equality.

Change all of your conditionals. Ex:

if (operator.equals("+")
Michael
  • 776
  • 4
  • 19