计算器函数输出错误的值

时间:2017-10-23 16:10:44

标签: java

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));

    }
}

我希望此函数在执行操作时返回正确的值。但是,它始终返回0分配的初始值。请帮忙!!!

1 个答案:

答案 0 :(得分:0)

字符串比较应始终使用equals完成以下代码: -

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));

    }