Java字符串转化为运算符
为运算符定义接口,并将实例放在Map容器中,这样就可以将字符串和运算符之间做一个映射,完成转换。
·
为运算符定义接口,并将实例放在Map容器中,这样就可以将字符串和运算符之间做一个映射,完成转换。
public class CompareUtil {
public interface Operation {
boolean calculate(int a, int b);
}
public static final Map<String, Operation> opMap = new HashMap<>();
static {
opMap.put(">", ((a, b) -> a > b));
opMap.put(">=", ((a, b) -> a >= b));
opMap.put("<", ((a, b) -> a < b));
opMap.put("<=", ((a, b) -> a <= b));
opMap.put("=", ((a, b) -> a == b));
}
}
然后测试
public class test {
public static void main(String[] args) {
String str = ">";
int ab = 3;
int ac = 2;
boolean res = CompareUtil.opMap.get(str).calculate(ab,ac);
System.out.println("ssssssss" + res);
}
}
更多推荐



所有评论(0)