Why is this result giving as 0 in Java? [closed]

-1

I'm doing a program that has a small simple calculator, basically the user will have the mathematical expressions (+, -, *, /) and you can choose between one of them and then the result will appear on the screen. But for some reason it is not working and it returns 0 as the result.

My code:

        int n1 = 20; //o primeiro número
        int n2 = 20; //o segundo número
        int res = 0;
        String op;

        op = JOptionPane.showInputDialog("+ " + 
            "\n - " + 
            "\n * " +
            "\n /");

        if(op == "+") {
            res = n1+n2; //retorna 0, ao invés de 40.
        }
        else if(op == "-") {
            res = n1-n2;//somente aqui que deve retornar 0.
        }
        else if(op == "*") {
            res = n1*n2;//retorna 0, ao invés de 400.
        }
        else if(op == "/") {
            res = n1/n2;//retorna 0, ao invés de 1.
        }

        JOptionPane.showMessageDialog(null, "Result : " + res);
    
asked by anonymous 16.07.2017 / 04:39

1 answer

1

I was able to find the error, it was in if where it jumped the check part inside the if and returned 0 as the result because res = 0 .

My code is neat:

        int n1 = 20;
        int n2 = 20;
        int res = 0;
        String op;

        op = JOptionPane.showInputDialog("+ " + 
            "\n - " + 
            "\n * " +
            "\n /");

        if(op.equals("+")) {
            res = n1+n2;
        }
        else if(op.equals("-")) {
            res = n1-n2;
        }
        else if(op.equals("*")) {
            res = n1*n2;
        }
        else if(op.equals("/")) {
            res = n1/n2;
        }

        JOptionPane.showMessageDialog(null, "Result : " + res);
    
16.07.2017 / 04:47