java编程,用代码实现计算器类(Calculator)

1个回答

  • public class Calculator {

    private int number1;

    private int number2;

    public Calculator(int number1, int number2) {

    this.number1 = number1;

    this.number2 = number2;

    }

    public double add() {

    return number1 + number2;

    }

    public double subtract() {

    return number1 - number2;

    }

    public double multiple() {

    return number1 * number2;

    }

    public double divide() {

    if(number2 == 0) {

    return 0;

    }

    return number1 / number2;

    }

    }

    public class TestCalculator {

    public static void main(String[] args) {

    Calculator calculator = new Calculator(5, 2);

    System.out.println(calculator.add());

    System.out.println(calculator.subtract());

    System.out.println(calculator.multiple());

    System.out.println(calculator.divide());

    }

    }