使用接口编写对任意两个数进行四则运算的Java程序
时间: 2024-05-27 12:14:58 浏览: 74
interface Calculator {
int add(int x, int y);
int subtract(int x, int y);
int multiply(int x, int y);
int divide(int x, int y);
}
class BasicCalculator implements Calculator {
public int add(int x, int y) {
return x + y;
}
public int subtract(int x, int y) {
return x - y;
}
public int multiply(int x, int y) {
return x * y;
}
public int divide(int x, int y) {
if (y == 0) {
throw new IllegalArgumentException("Cannot divide by zero!");
}
return x / y;
}
}
class Main {
public static void main(String[] args) {
Calculator calculator = new BasicCalculator();
int x = 10;
int y = 5;
System.out.println("x + y = " + calculator.add(x, y));
System.out.println("x - y = " + calculator.subtract(x, y));
System.out.println("x * y = " + calculator.multiply(x, y));
System.out.println("x / y = " + calculator.divide(x, y));
}
}
阅读全文