Why is this result giving as 0 in Java?

Asked

Viewed 84 times

-1

I’m making a program where you have a small and 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 as 0 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);

1 answer

1


I was able to find the error if where he skipped the verification part inside the if and returned as 0 the result because res = 0.

My neat code :

        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);
  • Please mark your answer as a solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.