用java代码创建一个计算类,实现加减乘除运算 并写出测试类
时间: 2024-02-16 10:03:31 浏览: 104
下面是一个简单的 Java 计算器类和测试类:
```java
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return a / b;
}
}
```
测试类:
```java
public class CalculatorTest {
public static void main(String[] args) {
int a = 10;
int b = 5;
System.out.printf("%d + %d = %d%n", a, b, Calculator.add(a, b));
System.out.printf("%d - %d = %d%n", a, b, Calculator.subtract(a, b));
System.out.printf("%d * %d = %d%n", a, b, Calculator.multiply(a, b));
System.out.printf("%d / %d = %d%n", a, b, Calculator.divide(a, b));
}
}
```
输出:
```
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2
```
阅读全文