Java turns a string into an arithmetic expression

Source: Internet
Author: User

Generally involved in the calculation will be used in the configuration, in the background to configure, but basically will be tangled in how to pass the value in and determine the output data

Package com.study.day01;

Import Javax.script.ScriptEngine;
Import Javax.script.ScriptEngineManager;
Import javax.script.ScriptException;

public class Expresstest {

public static void Test1 () throws Scriptexception {
STR is a formula defined in the database
String str = "X<=1?5:X<=2?10:X<=5?15:20";
Scriptenginemanager manager = new Scriptenginemanager ();
ScriptEngine engine = Manager.getenginebyname ("JS");
The form of a key-value pair will (7), where 7 is a constant, but the value in the project is a variable
Engine.put ("X", 7);
Object result = Engine.eval (str);
SYSTEM.OUT.PRINTLN ("Result type:" + Result.getclass (). GetName () + ", calculation result:"
+ result);
}

public static void Main (string[] args) throws Scriptexception {
Test1 ();

}
}

Java turns a string into an arithmetic expression

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.