检测java中存储为字符串的运算符的类型 [英] Detecting type of operator stored as string in java

查看:93
本文介绍了检测java中存储为字符串的运算符的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java程序中,我有这些字符串:

In a Java program, I have these strings:

a= 8,7,"+"
b=1,5,"*"

每一行都是一个单独的过程。我想在每一行中,用该运算符计算两个数字。但我不想使用任何类型的条件系统来检测每行中的哪个运算符。

Each line is a separate process. I want in each line, that two number calculated with that operator. But I don't want to use any type of condition system for detecting which operator is in each line.

事实上,我的主要问题是无条件地检测运营商的类型。我不想使用Javascript引擎。我想知道是否有任何有效和标准的方法。

In fact, my main problem is detecting the type of the operator without conditions. I don't want to use the Javascript engine. I want to know is there any efficient and standard way.

推荐答案

J. Selva回应的另一个解决方案:

Another solution from J. Selva's response:

改进


  1. 单一班级

  2. 静态块

  3. 更好的抽象

import java.util.HashMap;
import java.util.Map;

import java.util.HashMap; import java.util.Map;

/**
 * Created by SEA-HAWK on 23/8/15.
 */
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,"*"=200
20,10,"+"=30
20,10,"-"=10
20,10,"/"=2

注意:更改浮点/小数值计算的数据类型。

Note: change datatype for float/decimal value computation.

这篇关于检测java中存储为字符串的运算符的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆