java编写多运算符计算器
时间: 2024-09-13 13:16:15 浏览: 36
在 Java 中编写一个多运算符计算器,可以创建一个实现了基本运算(如加、减、乘、除)以及更复杂运算(如取余、幂等)的 Calculator 类。这个类通常会包含一些方法,比如:
```java
public class Calculator {
public double add(double a, double b) {
return a + b;
}
public double subtract(double a, double b) {
return a - b;
}
public double multiply(double a, double b) {
return a * b;
}
public double divide(double a, double b) throws ArithmeticException {
if (b != 0) {
return a / b;
} else {
throw new ArithmeticException("Division by zero is not allowed");
}
}
public double modulo(double a, double b) throws ArithmeticException {
if (b != 0) {
return a % b;
} else {
throw new ArithmeticException("Modulo operation requires a non-zero divisor");
}
}
public double power(double base, double exponent) {
return Math.pow(base, exponent);
}
}
```
用户可以通过创建 Calculator 对象并调用相应的计算方法来执行操作,例如:
```java
Calculator calc = new Calculator();
double result = calc.add(5, 3); // 结果为8
result = calc.subtract(10, 7); // 结果为3
try {
result = calc.divide(10, 2); // 结果为5
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
```
阅读全文