模拟一个简单的计算器,通过静态工具Tools,实现加减乘除的运算
时间: 2024-02-21 19:59:25 浏览: 72
好的,以下是一个简单的计算器的静态工具类的实现,包含加减乘除四种基本的运算:
```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 double divide(int a, int b) throws IllegalArgumentException {
if (b == 0) {
throw new IllegalArgumentException("Cannot divide by zero");
}
return (double) a / b;
}
}
```
可以通过以下代码进行测试:
```java
public static void main(String[] args) {
int a = 10;
int b = 5;
System.out.println("a + b = " + Calculator.add(a, b));
System.out.println("a - b = " + Calculator.subtract(a, b));
System.out.println("a * b = " + Calculator.multiply(a, b));
try {
System.out.println("a / b = " + Calculator.divide(a, b));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
```
输出结果为:
```
a + b = 15
a - b = 5
a * b = 50
a / b = 2.0
```
阅读全文