0

Hi I am building a simple calculator program, wherein there is a double num1, double num2, string myOperator. For instance the values may hold the following respectively: 1, 2, "+". This would later equate to the equation 1 + 2 = 3;. For my gui I have number buttons, and operation buttons (+,-,/,*) that set the variables value.

public double num1, num2, num3;
public String myOperator; 

Here is my method:

    @FXML
    private void handleSolution(ActionEvent event){
        if(myOperator == "+"){
            System.out.println("plus");
        }else if(myOperator == "-") {
            System.out.println("minus");
        }else if(myOperator == "*"){
            System.out.println("multiplication");
        }else if(myOperator == "/"){
            System.out.println("division");
        }else{
            System.out.println("wtf");
            System.out.println(myOperator);
            System.out.println(myOperator.length());
        }
    }

Regardless of which button I click (+,-,/,*) in the gui, 'wtf' is always printed, so I added myOperator to see what is actually printed out and myOperator.length to see if I perhaps had the correct character, but added a space incorrectly.

Here were my results:

If I press the [+] button the system prints out:

+
1

If I press the [-] button the system prints out:

-
1

If I press the [/] button the system prints out

/
1

If I press the [*] button the system prints out:

*
1

Can anyone tell me how to fix this or what I am doing incorrectly?

mdash1
  • 1,115
  • 4
  • 17
  • 31
  • Dont use `==` to check for equality but equals. – dpr Jan 06 '18 at 22:12
  • Objects and primitives work quite differently in Java. If you declared the operator variable as a `char` primitive ( `public char myOperator`) and put the operators inside single quotes in the if statements, this would work. But because `String`s are objects, you need to use `equals()` to compare the _content_ of the string. – Mick Mnemonic Jan 06 '18 at 22:15

0 Answers0