java两数加减乘除代码_java中⽤抽象类做两个数的相加减乘除
操作
public class Test {
public static void main(String[] args) {
double num1 = 30;
double num2 = 15;
System.out.println("加: " + Instance("+").eval(num1, num2));
System.out.println("减: " + Instance("-").eval(num1, num2));
System.out.println("乘: " + Instance("*").eval(num1, num2));
System.out.println("除: " + Instance("/").eval(num1, num2));
}
}
import java.util.HashMap;
import java.util.Map;
public abstract class Operation {
private static Map register = new HashMap();
private Operation(String operator) {
register.put(operator, this);
}
public final static Operation ADD = new Operation("+") {
protected double eval(double left, double right) {
return left + right;
}
};
public final static Operation SUBTRACTION = new Operation("-") {
protected double eval(double left, double right) {
return left - right;
}
};
public final static Operation MULIPLICATION = new Operation("*") {
protected double eval(double left, double right) {
return left * right;
}
eval是做什么的
};
public final static Operation DIVISION = new Operation("/") { protected double eval(double left, double right) {
return left / right;
}
};
public static Operation getInstance(String operator) {
Operation op = (operator);
if (op == null) {
throw new IllegalArgumentException("不能进⾏ " + operator + " 运算"); }
return op;
}
protected abstract double eval(double left, double right);
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论