J. Selva回应的另一个解决方案:
改进之处
- 单班
- 静态块
- 更好的抽象
导入java.util.HashMap; 导入java.util.Map;
public abstract class Expr { public static Map<String,Object> op; static{ op=new HashMap<>(); op.put("+", new Expr() { @Override public int evaluate(int a, int b) { return a + b; } }); op.put("-", new Expr() { @Override public int evaluate(int a, int b) { return a - b; } }); op.put("*", new Expr() { @Override public int evaluate(int a, int b) { return a * b; } }); op.put("/", new Expr() { @Override public int evaluate(int a, int b) { return a / b; // decimal point loss } }); } abstract public int evaluate(int a, int b); public static int expreval(String expr){ String a[]=expr.split(","); a[2]=a[2].replaceAll(""",""); return ((Expr)op.get(a[2])).evaluate(Integer.parseInt(a[0]),Integer.parseInt(a[1])); }}
主功能:
public static void main(String[] args) { String x="20,10,"*""; System.out.println(x+"="+Expr.expreval(x)); x="20,10,"+""; System.out.println(x+"="+Expr.expreval(x)); x="20,10,"-""; System.out.println(x+"="+Expr.expreval(x)); x="20,10,"/""; System.out.println(x+"="+Expr.expreval(x));}
输出:
20,10,"*"=20020,10,"+"=3020,10,"-"=1020,10,"/"=2
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)