Evaluate a string

Hi,
I have a string that contains a logical expression, for example String str="(true | false) & true".
I want to evaluate this expression just like if it was a boolean.
So I would like to write
if (str) { int test=0; }But this piece of code is wrong. I need a function "eval" that evaluate the expression contained in str, so that I can write
if (eval(str)) { int test=0; }How can I do ? Thank you for your answers

Never worked with it yet, but have a look at the javax.script package (since java 1.6).
Piet

Similar Messages

  • Evaluate a string containing a constant name

    Hi,
    how can I evaluate a string containing a constant name
    such as
    String a= " Integer.MAX_INT";
    thx a lot,
    tiz

    Er...no. Integer.MAX_INT is an int, and you can't call methods on primitive types. :-)
    What you might need to do is check for these constants and set the values yourself. Otherwise you'll have a load of difficulty parsing strings and what-not.

  • Is there any scripting library?or a way to evaluate mathimatical strings?

    by evaluating strings i mean things of the type
    evaluate("5+3-2+sin(5)") should return some value, i know that in other languages, you will find libraries that define some scriptengine that can evaluate such strings, is this available in java aswell? 'Cause after searching i only found one for JavaScript, which is not what i'm looking for.
    It doesn't even have to be a scriptengine, just some sort of way i can use to, given some sort of mathematical string (with functions like sinus,POW,...) to evaluate it, it doesn't have to be able to recognise variables in it, but it would help but i'd be happy with just some library or anything that can implement this.
    Edited by: omegax on Apr 9, 2009 1:52 AM
    Edited by: omegax on Apr 9, 2009 1:53 AM

    omegax wrote:
    by evaluating strings i mean things of the type
    evaluate("5+3-2+sin(5)") should return some value, i know that in other languages, you will find libraries that define some scriptengine that can evaluate such strings, is this available in java aswell? 'Cause after searching i only found one for JavaScript, which is not what i'm looking for.The example you posted can be handled by the JavaScript engine shipped with Java 1.6 (although you'll have to change sin(...) to Math.sin(...)):
    ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
    System.out.println(engine.eval("Math.sin(45)"));

  • Evaluate String Expression

    Hi all,
    I am trying to evaluate a string expression against rows of data. If the data satisfys that condition/expression then its selected otherwirse its not.
    To re-iterate how to evaluate a string expression like: "value < 1"
    against data values like: 0, 1, 2 ...n
    Any help will be appreciated. Thanks in advance.
    Here's the code I am using:
          * Evaluates the Expression Either return True or False
          * @return
      public boolean evalExpression() {
              boolean retval = true;
              // Identify the conditional process step
              if (this.isConditional()) {
                   // get the inputs
                   for (int i = 0; i < myInputs.size(); i++) {
                        ContainerDataElement containerDataElement = (ContainerDataElement) myInputs
                                  .elementAt(i);
                        String data = containerDataElement.getValueAsString();
                                            // Get the conditions
                        for (int j = 0; j < myProcessConditions.size(); j++) {
                             ProcessCondition pc = (ProcessCondition) myProcessConditions
                                       .elementAt(j);
                                  Boolean condition = new Boolean(pc.getExpression());
                                                      // Evaluate the expression against the data elements
                             if (condition.booleanValue()) {
                                  retval = true;
                             else {
                                  retval = false;
              return retval;
         }

    ProcessCondion holds the Expression but I need to match the value the expression matches.
    A bit like equals example I am trying out now:
      public boolean evalExpression() {
              boolean retval = true;
              // Identify the conditional process step
              if (this.isConditional()) {
                   // get the inputs
                   for (int i = 0; i < myInputs.size(); i++) {
                        ContainerDataElement containerDataElement = (ContainerDataElement) myInputs
                                  .elementAt(i);
                        String data = containerDataElement.getValueAsString();
                        com.aim.common.DebugLog.debug("dataELEMENTS--------"
                                  + data.toString());
                        // Get the conditions
                        for (int j = 0; j < myProcessConditions.size(); j++) {
                             ProcessCondition pc = (ProcessCondition) myProcessConditions
                                       .elementAt(j);
                             com.aim.common.DebugLog.debug("ProcessCondition--------"
                                       + pc.toString());
                             Boolean condition = new Boolean(pc.getExpression());
                             com.aim.common.DebugLog.debug("condition--------"
                                       + condition.toString());
                             // Evaluate the expression against the data elements
                             if (containerDataElement.equals(condition)) {
                                  com.aim.common.DebugLog.debug("conditionEVALUATED--------"
                                            + retval);
                                  retval = true;
                             else {
                                  retval = false;
              return retval;
         }

  • Programmat​ically altering strings to be evaluated in a Formula Node?

    Hello,
    I want the user of my program to enter an expression in a string control
    that is a function of two variables. I want to be able to evaluate this
    string as if it were in a formula node.
    Is there a way of programmatically altering strings to be evaluated in a
    Formula Node?
    Thanks,
    Peter

    I found 'Eval Formula Node.vi'. That does just what I was looking for.
    Thanks
    Peter
    "Peter T" wrote in message news:3d810eba@newsgroups....
    > Hello,
    >
    > I want the user of my program to enter an expression in a string control
    > that is a function of two variables. I want to be able to evaluate this
    > string as if it were in a formula node.
    >
    > Is there a way of programmatically altering strings to be evaluated in a
    > Formula Node?
    >
    > Thanks,
    >
    > Peter
    >
    >

  • Evalutate a string containing a numeric expression

    I need a function which would evaluate a string containing numbers and operators like "1+1" and return 2. The function should take into account precedence and all arithmetic and logical operators
    Thanks
    Mita

    Why don't you use the JDK compiler APIs (com.sun.javac.Main class) to compile on the fly a class implementing this interface:
    public interface Evaluator {
    public double evaluate() {
    return xxx;
    where xxx is your expression?
    Obviously, you build this class' source at runtime when you get the expression as input, and after you compile it you load it with Class.ForName(), instanciate it with newIstance() and the call the "evaluate" method.
    The advantage of this approach is that you can use "automagically" every expression available in java language. And with some extra effort of text-processing, even the Math functions!!!
    Giorgio Maone

  • How I can catch the word that was spoken in a string??

    Hi
    i'm doing a java aplication with speech recognition jsapi and i want know how  i can convert tag form FinalRuleResult  to string??
    i want  catch the word that was spoken in a string to  evaluate the string in the sentences if                               
    this is the code that i have developed:
    public static void main(String[] args)
         {prueba inst = new prueba();
                   inst.setVisible(true);
              try {
                   RecognizerModeDesc descripcion = new RecognizerModeDesc(null, Boolean.TRUE);
                   SpeechEngineChooser chooser = SpeechEngineChooser.getRecognizerDialog(descripcion);
                   chooser.show();
                   descripcion = chooser.getRecognizerModeDesc();
                   reconocedor = Central.createRecognizer(descripcion);
                   reconocedor.addEngineListener(new TestEngineListener());
                   RecognizerAudioAdapter raud = new TestAudioListener();
                   reconocedor.getAudioManager().addAudioListener(raud);
                   reconocedor.allocate();
                   reconocedor.waitEngineState(Recognizer.ALLOCATED);
                   RuleSequence secuencia = new RuleSequence();
                   RuleTag comando1 = new RuleTag(new RuleToken("vol"),"VOL");
                   RuleTag comando2 = new RuleTag(new RuleToken("channel"),"CHANNEL");
                   RuleTag comando3 = new RuleTag(new RuleToken("end"),"END");
                   RuleTag comando4 = new RuleTag(new RuleToken("up"),"UP");
                   RuleTag comando5 = new RuleTag(new RuleToken("down"),"DOWN");
                   RuleAlternatives comandos = new RuleAlternatives();
                   comandos.append(comando1);
                   comandos.append(comando2);
                   comandos.append(comando3);
                   secuencia.append(comandos);
                   RuleGrammar gramatica = reconocedor.newRuleGrammar("basepatrones");
                   gramatica.setRule("testRule",secuencia,true);
                   gramatica.setEnabled(true);
                   reconocedor.suspend();
                   reconocedor.commitChanges();
                   reconocedor.waitEngineState(Recognizer.LISTENING);
                   reconocedor.requestFocus();
                   reconocedor.resume();
                   reconocedor.addResultListener(new ResultAdapter() {
                        public void resultAccepted(final ResultEvent e)
                             try {
                                  FinalRuleResult r = (FinalRuleResult)(e.getSource());
                                  System.out.println("Obtenido el resultado "+r);
                                  String tags[] = r.getTags();
    if(tags == null) return;
                        //comparacion de :::     
    // in this point i want catch the word that was spoken in a string to evaluate the string in the sentences if                               
                                  if(tags[0].equals("VOL"))
                                       JOptionPane.showMessageDialog(null,"has selecciuonado el volumen");
                                       jLabel1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("control/controltv+.gif")));
                                       enviar("s");     
                                  if(tags[0].equals("CHANNEL"))
                                            JOptionPane.showMessageDialog(null,"QUIERES CAMBIAR CANAL???");
                                            jLabel1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("control/controlt0.gif")));
                                            enviar("c");
                                  if(tags[0].equals("END"))
                                  JOptionPane.showMessageDialog(null,"SESION DE RECONOCIMIENTO TERMINADA");
                                  jLabel1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("control/controlt1.gif")));
                                  System.exit(-1);
                                  else return;
                             } catch(Exception e1) {}
              } catch (Exception e) {
                   e.printStackTrace();
                   System.exit(-1); }
         }

    I donot know about Java Speech API.
    But it is possible to recognize with Sphinx API.
    you get it from [http://cmusphinx.sourceforge.net/sphinx4/]

  • Evaluating a String to XML element

    we had a xquery function
    getProductRepo($columnSelect as xs:int) as ns0:productVal
    for $productval in ns11:getProductVal()
    return
    <ns0:ProductVal>
    <repo1>fn:data($productval/val)</repo1>
    <repo2>fn:data($productval/val)</repo2>
    <repo3>fn:data($productval/val)</repo3>
    for $columnSelect in ns12:ColumnSelect()/module
    let $columnVal=$columnSelect[$columnSelect]/column
    <optionalElem?>fn:data($productval/$columnVal)</optionalElem>
    </ns0:ProductVal>
    in <optionalElem> we are expecting value is fn:data($productval/TotalProducts) ie "Arial".But we are getting TotalProducts ie the value of $columnVal.
    is any method in xquery/xpath to evaluate a string to element name.
    like eval().

    Can you please post a clear description of your problem? I have no idea why you expect $productval/TotalProducts to be "Arial".
    XQuery functions and operators can be found at
    http://www.w3.org/TR/xpath-functions/
    Are you looking for something like node-name( node ) ?

  • "cleaning" a string

    I need to strip special characters out of a string field.  Anyone know of a function or technique in Crystal Reports (XI R2) that can evaluate a string and return only the letters?  The characters themselves can vary and can occur more than once in the string.  Example: I have "Jennifer Hanson_CPA #" and would to extract "JenniferHanson" or "Jennifer Hanson".  Any suggestions would be appreciated.

    Thank you.  That loop works well.  Needed to add a line to reset result variable to blank so it didn't swell.  Was getting results like this:
    Jimmy Nuetron
    Jimmy Nuetron Larry Ellison
    Jimmy Nuetron Larry Ellison Marc Beniof
    Final code is this:
    stringvar strval:= {Sheet1_.Name};
    stringvar array schars:= ['#','%','+','_','.','-']; 
    stringvar res;
    numbervar i;
    res:= '';
    for  i:= 1 to len(strval)
    do
    if not (strval<i> in schars)  then
    (res:= res & strval<i>;);
    res;
    thanks again!!
    Edited by: Darrin Farnsworth on Nov 24, 2008 11:10 PM

  • Evaluating String Formulas

    I was wondering if anyone knew of a library or methods in existing J2SE API that would allow me to evaluate a string formula to a double.
    For example, if I had the following code:
    Double test;
    String formula = new String("12.5 + 15 * 4");
    /* What can I do here to make this work */
    test = new Double(formula);This would result in a NumberFormatException, because the Double constructor can't resolve the string to a double value.
    Anyone have an idea of how to solve this without building my own extensive method with StringTokenizer, etc.
    Thanks in advance.

    Unfortunately, the formula is entered by a user in a configuration file and stored as a string to start.
    The reason is that the user doesn't actually put the values in, rather markers for fields from a database. My application replaces these markers with the actual values. And that is why it is in String format.

  • Evaluating strings as literals

    Is there an easy way to evaluate a string like "myVar.property.value <= myOtherVar.property.value" against run-time literal values? The format will always be the same,  but breaking it into 3 parts, running a switch...case through all the operators then trying to convert the strings seems awful cumbersome....

    I have a demo here you might find useful
    MyClass.as
    package 
        import flash.text.TextField;
        public class MyClass
            public var tf:TextField;
            public function MyClass()
                tf = new TextField();
                tf.text = "somthing or other";
    and
    package
        import flash.display.Sprite;
        import flash.events.Event;
        [SWF(backgroundColor="#ffffff", width=400, height=400, frameRate=60)]
        public class Main extends Sprite
            public function Main()
                if (stage)
                    init();
                else
                    addEventListener(Event.ADDED_TO_STAGE, init);
            public function init(event:Event=null):void
                removeEventListener(Event.ADDED_TO_STAGE, init);
                var myClass:MyClass = new MyClass();
                var string:String = "tf.text.length";
                var values:Array = string.split(".");
                trace(myClass[values[0]][values[1]][values[2]]);
    I can't currently think of a way to get hold of the myClass instance though

  • Calculating double from String

    Hello again
    I just have a quick question here, that confused me a bit (though I guess it makes sense)
    If I try to print the double 1 + 2 * 3, it will output 7.
    But I have a JTextField with the string 1 + 2 * 3, and I try to parse it as a double, it won't let me.
    Am I doing something since it doesn't work? To me it seems logic that it should be able to parse a string as a double, if it can calculate the double without a problem.
    Do you have any ideas?
    Any help here is appreciated
    Thanks in advance
    Ulverbeast
    Edited by: Ulverbeast on Feb 25, 2010 1:07 PM

    Ulverbeast wrote:
    But in the second example it tries to parse the whole string as a double?As far as Java is concerned, a string is just a bunch of characters. Java doesn't know that this particular string happens to be a mathematical expression that could be evaluated.
    If you want to evaluate a string as a mathematical expression you can do that out-of-the-box if you are using Java 6, through the new ScriptEngine functionality. Java 6 ships with a script engine that can evaluate JavaScript, so in this case you could do:
    import javax.script.*;
    public class EvalExample {
        public static void main(String[] args) {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
            try {
              Double result = (Double) jsEngine.eval("1 + 2 * 3");
              System.out.println(result);
            } catch (ScriptException ex) {
              ex.printStackTrace();
    }(Note that the cast to Double will fail if the expression you evaluate does not result in a number.)
    Edited by: Torgil on Feb 25, 2010 8:12 PM: Figured I should make the example an SSCCE :)

  • Evaluating binary strings with "Don't care" conditions

    I frequently have to evaluate binary strings or register values for particular bits. Does anyone have a better way? And if not, perhaps this is a suggestion for NI.
    To this point I've used two methods:
    1. I turn the data into an actual string in my CVI code and inject X's in the necessary positions. I then perform a string evaluation for equivalence, the string now consisting of '1's '0's and 'x's.
    2. Bring the data into the teststep and applying an expression to the data source, masking the appropriate bits. Then evaluate as a numeric with a value that assumes the offended bits "zeroness" or "oneness" depending on how I've implemented.
    The first was one requires specialized code, but allows for a little more visibility (in the code at least) of which bits are designated as DCs. But translating a multiple byte and variable length of amount of information into a string is cumbersome. Sure the code is reusable, but I'm not convinced the translation is necessary or best.
    The second buries the mask in a window that is, seemingly, infrequently used. I've had colleagues work on a project behind me trying to figure out where the value was being manipulated because I've applied a mask via the source. My original explanation of "ninjas" wasn't well taken...
    It seems like it would be ideal for the limits window to allow the use of "X"s when defining a "binary" type comparison so that the mask is clearly defined in the limit itself, and the data as it's passed to and from teststand remains untouched. Also, if this were to be implemented I would hope the property loader would support it.
    Am I missing a much easier way to do this? Anyone have a better way?
    Thanks in advance!
    Colt.
    P.S. Why isn't "NI" and "CVI" built into the spell checker?

    So in that first case where I am using CVI to "insert" I am building a string type vector that contains ASCII '1's '0's and 'x's. Where the Xs are in the binary position for what I am considering as "don't care".
    So say for instance I was converting a piece of data that was 0xEB, with bit 0 being considered a DC for evaluation, I would build a string like "1110 101X" . This string is what I would pass back to teststand. In teststand I would then perform an equivalence test between the two strings.
    For the second question about an implementation for the limit, say I open the test step, click on "Edit Limits" then from the drop down in the bottom right I select "Binary". I could then compose a limit in a similar form as described above. Where the limit box could contain something like "0b1110101X". But as for the data I hand to teststand, it would still be just a scalar value, with no masks applied. In the code, or in teststand.
    Sorry if I'm not making any sense! I hardly ever do...
    Colt.

  • Reading A String From A File

    Having Difficulties Parsing a file for specific information. How do you either convert a int (from the read class) to a stream or how do you read a stream directly from a file?
    Also need to know how can ensure that tags within an XML document do not overlap...
    any help is appreciated -- thank you...
    import java.io.*;
         public class Check
         public static void main(String[] args) throws IOException
              if (args.length != 1)
                   System.out.println("JAVA Check <doc.xml>");
                   return;
              String fileName;
              fileName = args[0];
              if (fileName.endsWith(".xml"))
                   System.out.println("THE FILE IS A VALID XML FILE");
                   else
                   System.out.println("NOT A VALID XML FILE");
              File inFile=new File(args[0]);
              FileReader fr=new FileReader(inFile);
              File outFile=new File(args[0]);
              FileWriter fw=new FileWriter(outFile);
              String frontopentag = "<";
                   Check fot=new Check();
                   int countfrontopentag = 0;
              String frontclosetag = "</";
                   Check fct=new Check();
                   int countfrontclosetag = 0;
              String backclosetag = ">";
                   Check bct=new Check();
                   int countbackclosetag = 0;
              int c=0;
              c=fr.read();
              while (c != -1)
                   fw.write(c);
                   c=fr.read();
                        if (fot.equals("<"))
                        ++countfrontopentag;
                        return;
                        if (fct.equals("</"))
                        ++countfrontclosetag;
                        return;
                        if (bct.equals(">"))
                        ++countbackclosetag;
                        return;
                        if (countfrontopentag != countfrontclosetag)
                        System.out.println("CHECK THAT THE OPENING OF THE TAGS ARE BALANCED, '<...' AND '</...'");
                        else
                        System.out.println("OPENING TAGS ARE BALANCED, '<...' AND '</...'");
                        if(countbackclosetag%2 == 0)
                        System.out.println("CLOSING TAGS ARE BALANCED, '...>'");
                        else
                        System.out.println("CHECK THAT THE CLOSING TAGS ARE BALANCED, '...>'");
                        if((2*countbackclosetag) != countfrontopentag)
                        System.out.println("CHECK THAT THE NUMBER OF '<...' AND '</...' EQUALS THE NUMBER OF CLOSING TAGS, '...>'");
                        else
                        System.out.println("THE NUMBER OF '<...' AND '</...' EQUALS THE NUMBER OF CLOSING TAGS, '...>'");
              fr.close();
              fw.close();
              } //close main
         } //close class

    Well... I have no idea of how much java you know, so please forgive me if I state something you already know by heart.
    your best bet for the integer is reading by characters,
    testing them, (Character.isDigit(a valid character)) and the Character.digit(char ch, int radix) method.
    char ch;
    forloop
    ch = aString.charAt(i);
    if (Character.isDigit(ch))
    while your best bet for overlapping brackets and such would be to use a number, and add to it whenever there is a left-hand bracket, and subtract from it, whenever there is a right-hand bracket. or use a stack to save the characters within the brackets and then, whenever you find a right-hand bracket, evaluate the string up to the point of the last left-hand bracket.

  • Read a CSV file and dynamically generate the insert

    I have a requirement where there are multiple csv's which needs to be exported to a sql table. So far, I am able to read the csv file and generate the insert statement dynamically for selected columns however, the insert statement when passed as a parameter
    to the $cmd.CommandText
    does not evaluate the values
    How to evaluate the string in powershell
    Import-Csv -Path $FileName.FullName | % {
    # Insert statement.
    $insert = "INSERT INTO $Tablename ($ReqColumns) Values ('"
    $valCols='';
    $DataCols='';
    $lists = $ReqColumns.split(",");
    foreach($l in $lists)
    $valCols= $valCols + '$($_.'+$l+')'','''
    #Generate the values statement
    $DataCols=($DataCols+$valCols+')').replace(",')","");
    $insertStr =@("INSERT INTO $Tablename ($ReqColumns) Values ('$($DataCols))")
    #The above statement generate the following insert statement
    #INSERT INTO TMP_APPLE_EXPORT (PRODUCT_ID,QTY_SOLD,QTY_AVAILABLE) Values (' $($_.PRODUCT_ID)','$($_.QTY_SOLD)','$($_.QTY_AVAILABLE)' )
    $cmd.CommandText = $insertStr #does not evaluate the values
    #If the same statement is passed as below then it execute successfully
    #$cmd.CommandText = "INSERT INTO TMP_APL_EXPORT (PRODUCT_ID,QTY_SOLD,QTY_AVAILABLE) Values (' $($_.PRODUCT_ID)','$($_.QTY_SOLD)','$($_.QTY_AVAILABLE)' )"
    #Execute Query
    $cmd.ExecuteNonQuery() | Out-Null
    jyeragi

    Hi Jyeragi,
    To convert the data to the SQL table format, please try this function out-sql:
    out-sql Powershell function - export pipeline contents to a new SQL Server table
    If I have any misunderstanding, please let me know.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna
    TechNet Community Support

Maybe you are looking for

  • Need to send a Report to user

    Hi All. Any idea's on the following requirement.   Actually, we need to send quarter data to the user in FIGL data, Below are the fields, Company code, Doc Number, Doc Type, Created on, Posting date, Ledger, Cost center, Item text. For these fields w

  • External Monitor Viewing - ALL FRAMES Unchecked

    Hello FCP gurus I cannot get a video signal on my external monitor. For some reason I have lost the ability to check the ALL FRAMES option in the View Menu under External Video. Each time I click ALL FRAMES it stays in the OFF mode. I think this may

  • Problem about TCP Socket

    I have made a File Transfer program using TCP. But I find a strange problem. The socket will be closed after sending a file..... Is my code wrong or the socket is this? Should I upload my code??

  • Af:commandLink not calling launchListener

    I'm using the dialog framework and it seems that when i use af:commandButton the launchListener binded method gets called, but when i use af:commandLink it doesn't. Is this a bug ? By the way, i have to use af:commandLink instead of af:commandButton

  • JAR file JDK version

    I have a question that i want to ask for a long time. Let say someone give you a jar file, how do we check which version of JDK it is compile ?