import java.util.Objects;
public class Calculator<T extends Number> {
public static <T extends Number> double add(T a, T b) throws NullPointerException {
//Objects.requireNonNull()
方法来检查传入的参数是否为空。
Objects.requireNonNull(a, "The first argument must not be null");
Objects.requireNonNull(b, "The second argument must not be null");
return a.doubleValue() + b.doubleValue();
}
public static <T extends Number> double subtract(T a, T b) throws NullPointerException {
Objects.requireNonNull(a, "The first argument must not be null");
Objects.requireNonNull(b, "The second argument must not be null");
return a.doubleValue() - b.doubleValue();
}
public static <T extends Number> double multiply(T a, T b) throws NullPointerException {
Objects.requireNonNull(a, "The first argument must not be null");
Objects.requireNonNull(b, "The second argument must not be null");
return a.doubleValue() * b.doubleValue();
}
public static <T extends Number> double divide(T a, T b) throws IllegalArgumentException, NullPointerException {
Objects.requireNonNull(a, "The first argument must not be null");
Objects.requireNonNull(b, "The second argument must not be null");
if (b.doubleValue() == 0) {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
return a.doubleValue() / b.doubleValue();
}
}
测试用例:
int result = Calculator.add(2, 3);
System.out.println(result); // 输出 5
double result2 = Calculator.divide(6, 3);
System.out.println(result2); // 输出 2.0
Calculator.add(null, 3); // 抛出 NullPointerException 异常