Converting inserted string to a compilable expression

后端 未结 5 1809
醉梦人生
醉梦人生 2021-01-23 07:45

I\'m somehow new to Java so my question can seem trivial, however i cannot find an answer to it anywhere in my books.

I want to initiatie a dialog with a user in which h

相关标签:
5条回答
  • 2021-01-23 07:59

    How to convert a String into Arithmetic Expression

    import bsh.*;
    
     class Operation
     {
    
        public static void main(String[] args)throws Exception
        {
            Interpreter i=new Interpreter();
            int r=(Integer)i.eval(args[0]);
            System.out.println(r);
        }
    }
    

    for this we need a separate jar file named: bsh.jar file

    need to set classpath for above jar file

    source: http://ohmjavaclasses.blogspot.com/2011/11/how-to-convert-string-into-arithmetic.html

    0 讨论(0)
  • 2021-01-23 08:01

    You have to write an expression parser to accomplish this kind of behaviour. There are a number of ways to accomplish this:

    1. Write your own expression parser using e.g. ANTLR.
    2. Include a scripting language (Jython, Beanshell, JavaScript...) and use that to parse and evaluate the expressions. The Java Scripting API can show you how to do this.
    0 讨论(0)
  • 2021-01-23 08:07

    There is no native facility in Java for evaluating strings as expressions. You must therefore do the work yourself.

    If you just want a quick and dirty solution, Javassist includes a snippet compiler allowing you to define a new class with your expression, and invoke it to get your result, after which you can discard it (i.e. run it in a separate classloader). It will require some work though :)

    http://www.jboss.org/javassist/

    0 讨论(0)
  • 2021-01-23 08:19

    You could also look at JScheme. Need to compile & run with the jscheme jar file.

    import jscheme.JS; 
    
    String query = "(+ 10 20)";
    System.out.println(query + " = " + JS.eval(query));
    

    See third example down at http://jscheme.sourceforge.net/jscheme/doc/userman.html#si

    JScheme main page at http://jscheme.sourceforge.net/jscheme/main.html

    0 讨论(0)
  • 2021-01-23 08:24

    It isn't so hard to parse them yourself, but if you need fast and probably accurate result, you can use one of the existing libraries to parse arithmetic expressions, like JEP or perhaps that Simple Parser for Arithmetic Expressions.

    See the Jep Console for a sample. It looks like Jep is payware. It might not be a problem, otherwise as I wrote, you should be able to find a number of equivalent libraries.

    0 讨论(0)
提交回复
热议问题