0
import java.util.* ;

class Main {
    public static double op(String operation, double number1, double number2) {
        double x = 0;
        if (operation == "+") {
            x = number2 + number1;
        }
        else if (operation == "x" || operation == "*") {
            x = number1 * number2;

        }
        else if (operation == "/" || operation == "÷") {
            x = number1 / number2;

        }
        else if (operation == "-") {
            x = number1 - number2;

        }
        else {
            System.out.println("Error: Please re-execute the program and try again!");
        }
        return x;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System. in );
        System.out.println("Please enter a number...");
        double x = input.nextDouble();
        System.out.println("Please enter an operation.... +, -, /, *");
        String y = input.next();
        System.out.println("Please enter your other number...");
        double z = input.nextDouble();

        System.out.println(op(y, x, z));

    }
}

I want this function to return the correct value when the operation is performed. However, it always returns 0 the initial value assigned. Please help!!!

luk2302
  • 55,258
  • 23
  • 97
  • 137

1 Answers1

0

String comparison should always be done using equals try the below code :-

public static double op(String operation, double number1, double number2) {
        double x = 0;
        if (operation.equals("+")) {
            x = number2 + number1;
        }
        else if (operation.equals("x") || operation.equals("*")) {
            x = number1 * number2;

        }
        else if (operation.equals("/") || operation.equals("÷")) {
            x = number1 / number2;

        }
        else if (operation.equals("-")) {
            x = number1 - number2;

        }
        else {
            System.out.println("Error: Please re-execute the program and try again!");
        }
        return x;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System. in );
        System.out.println("Please enter a number...");
        double x = input.nextDouble();
        System.out.println("Please enter an operation.... +, -, /, *");
        String y = input.next();
        System.out.println("Please enter your other number...");
        double z = input.nextDouble();

        System.out.println(op(y, x, z));

    }
Max08
  • 955
  • 1
  • 7
  • 16