Evaluating a String

Hi,
I'm trying to find a means of evaluating a mathematical expression contained within a String. For example, the string might be:
4*2 + (34/(4 -3)), where the output of the function is a solved numberical value, in this case 42.
I haven't been able to find anything in Java, although functions like this exist in javascript and even BBC basic (EVAL). Does anyone know where I can find something like this?
Cheers,
Pete Frederick

You need to parse it. The easiest thing to do is converting it to postfix and then evaluating. Note that the eval function works in JavaScript because it is interpreted and not compiled. I'm sure there are lots of examples to be found on the web that do this.
Kind regards,
  Levi

Similar Messages

  • 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.

  • 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 ) ?

  • Evaluating a string expression.

    hi,
    If have a string,which is an expression. how can i evaluate in java.
    for example
    " Monday in (Monday,Sunday,Tuesday) *And* 25 > 20 *OR* 9:00 between 8:00 and 10:00"
    Is there any api to evaluate the above the expression to give a Boolean value

    no. you have to:
    1/ create an interface "Criteria" with a single method "boolean parse();" defined in it
    2/ for each kind of expression, create a class implementing criteria, with a string as parameter in the constructor, and implements the parse() method so as it will be able to return "true" when the result of the expression is true, and false otherwise
    3/ when 1/ and 2/ are done, you can easily parse the complete expression (expr1 AND expr2 OR expr3) by splitting the complete expression on "AND" and "OR" statement, check what kind of criteria is expr1, expr2, and expr3, create the criteria by passing the expression as a parameter in the constructor of the appropriate class, call parse
    4/ make the sum of every parse() result
    if you're a java beginner, i suggest that you come back to this exercise later ; it won't be easy

  • Evaluating a String True/False with a Regular Expression

    I need to write a regular expression to make the following strings display the values of true/false:
    112 Elm Street True
    112 South Elm St. True
    112 S. Elm True
    Elm St. False
    South 112 Elm False
    Here's what I have so far:
    public class MethodOne
         public static void main (String args[])
              return street.matches (//d+//s+[A-Z]{1}[a-z][.]?//s{1}[A-Z]{1}[a-z]+[.]);
            String address1 = "112 Elm Address"
            String address2 = "112 South Elm St."
            String address3 = "112 S. Elm"
            String address4 = "Elm St."
            String address5 = "South 112 Elm"
            if (address1.matches(street) ) {
            System.out.println("True");
            else {
            System.out.println("False")
               }// end if
         Can anyone help me out?

    Is this what you want?
    String address1 = "112 Elm Street";
    String address2 = "112 South Elm St.";
    String address3 = "112 S. Elm";
    String address4 = "Elm St.";
    String address5 = "South 112 Elm";
    String matchString = "\\d+ [A-Z,a-z,. ]+";
    System.out.println(address1.matches(matchString));
    System.out.println(address2.matches(matchString));
    System.out.println(address3.matches(matchString));
    System.out.println(address4.matches(matchString));
    System.out.println(address5.matches(matchString));

  • CF10 is evaluating strings with comma's as complex types (Array), formerly they were just Strings

    Coldfusion 10's behaviour appears to have changed in the evaluation of strings with commas.
    Example:
    FORM.IDS = 123456, 654321, 789101  (Form Submission)
    <cfset fieldname="IDS" />
    <cfset test1 = FORM[fieldname] />
    <cfset test2 = evalute("FORM.#fieldname#") />
    In Coldfusion 9 the value of test1 and test2 is reported as "123456, 654321, 789101".
    In Coldfusion 10 the value of test1 and test2 is reported as an array. "Array (3)".
    Is this expected behaviour?  This is jacking up an application we are trying to upgrade and did not expect this one.  Any help will be much appreciated.
    Cheers
    Lee 

    ldavis101 wrote:
    Coldfusion 10's behaviour appears to have changed in the evaluation of strings with commas.
    Example:
    FORM.IDS = 123456, 654321, 789101  (Form Submission)
    <cfset fieldname="IDS" />
    <cfset test1 = FORM[fieldname] />
    <cfset test2 = evaluate("FORM.#fieldname#") /> [BKBK: typo corrected]
    In Coldfusion 9 the value of test1 and test2 is reported as "123456, 654321, 789101".
    In Coldfusion 10 the value of test1 and test2 is reported as an array. "Array (3)".
    Is this expected behaviour? 
    No, that is unexpected. Please report it as a bug.

  • String parsing - better solution needed :-(

    Hi Folks,
    Basically I will be taking in a string that represents the name of the output file the user wants, this will be specified in an xml file. The issue I have is that it needs to have non-static elements as part of the name as well (like a timestamp). This can come from two places: 1) the applications map 2)Predefined list of functions. Anything that will be comng from the map will have square brackets around it [], whilst anything the refers to a function will be inside curly brackets {}.
    So I may get a string in the form: filename_[user.id]_{datestamp}.pdf
    This should be output in a file called: filename_12345_2811208.pdf
    My issue is with evaluating the string, to determine what needs to be left as is, replaced with a value from a function, or replaced with a value from the map. I have looked at tokenizing the string and using indexof, but these are more trouble than they are worth. My current solution is, to have 4 booleans- one representing an open and close bracket of each type. When two matching booleans are true (i.e. detected an open and closed square bracket) take the sub-string between the brackets (to do this I use two ints representing the index of the brackets), evaluate it and append it to the output string.
    I have tested this and it works- but I was wondering if there is some other method that works better, as quite frankly my solution is the sort of embarassing crud you would see from a first year student programmer. Any help at all would be massively appreciated.
    Cheers,
    Max

    Hi swmtgoet_x,
    Thanks for the speedy reply- and your understanding of the problem is spot on.
    I had looked at the replace method- the only issue with that is that I have no way of knowing which value the users will want from the map (depending on how they have it implemented there could be hundreds of things in there), so to search the string for any value in the map would be hugely ineffecient :-(
    But having said that- I could look at using that approach for "pre-defined function"- I don't think there will be many of these, but in typical fashion no one has seen fit to gove me a list yet.....so I get to guess. :-s

  • Computing an expression in a string?

    I have an expression in a string, how can I compute this? I know I can put it in post fix and travers it with a Stack, but there must be an easier way in Java, e.g. How can I evaluation this string into an integer of 10?
    String s = "5+5";
    // how can I compute the expression in s???
    int i=???

    I appreciate the response, but have to agree with jschell
    With Java being an interpreted language, you would think it could resolve expressions built on the fly and residing in a string. I also see IDEs like IntelliJ that have an evaluate option in the debugger, so that is why I thought there might be a way. Perhaps they coded their own. I also saw a reference to an Expression Object, but could not make sense of it.
    If this issue of evaluatiing expressions in strings is a question has ben asked man times before, hopefully someone from Sun who works on the JDK is reading this, and considering adding this feature. I have seen this capability in another programming language, and have even seen the dynamic creation of programming statements built in strings.

  • Sorting images mislabeled in Report Attributes?

    I added some custom images in the Sorting section of the Report Attributes. When I ran the report the images displayed were opposite of what I expected (i.e. the descending image displayed for an ascending sort and vice versa.) Upon further investigation it appears that the labels in the Sorting section are indeed reversed. The descending image is displayed when the sort order is ascending and vice versa. Is this a bug?

    Erik,
    Thanks, this explains it. By specifying the request as part of your URL you run into the recently uncovered issue. The request you're setting is REMFROMLIST and ADD2LIST. You probably either have links that include those requests or you have branches where you specify them. Either way, in order to get reports sorting to work, you'll have to make sure that the request strings are not part of your URL. This is a work-around and the upcoming HTML DB patch release will solve this issue.
    One way of avoiding this is to have computations on the previous pages that set a napplication level or page level item to the REMFROMLIST and ADD2LIST values and then you can use those items for your conditions that are currently evaluating those strings.
    Hope this helps and sorry for the inconvenience,
    Marc

  • How to switch to a different JSP / EL implementation with WebLogic 10g?

    Hi everyone,
    we have a web application (JSP + servlets), that runs fine on Tomcat 5.5. We are porting it to WebLogic 10g3 - we've solved all of the issues except one. Some of the EL expressions are processes correctly in Tomcat, but it fails in WebLogic.
    For example we have a custom tag (component inherited from a SimpleTag), that renders a combobox. The component has "textExpression" attribute, that it evaluated like
    String text = (String) pageContext.getExpressionEvaluator().evaluate(textExpr, String.class, pageContext.getVariableResolver(), null);
    but if the expression has two parts - i.e. something like "{...} {...}" - the parse fails, for example with the following exception:
    javax.servlet.jsp.el.ELParseException: Error occured while trying to parse '${(option.partner.jmeno eq null && option.partner.prijmeni eq null && option.partner.nazevSpolecnostiFoPo ne null) ? option.partner.nazevSpolecnostiFoPo : option.partner.jmeno } ${(option.partner.jmeno eq null && option.partner.prijmeni eq null && option.partner.nazevSpolecnostiFoPo ne null) ? '' : option.partner.prijmeni}'
    weblogic.jsp.internal.jsp.el.ExpressionEvaluatorImpl.parseEL(ExpressionEvaluatorImpl.java:171)
    weblogic.jsp.internal.jsp.el.ExpressionEvaluatorImpl.parseExpression(ExpressionEvaluatorImpl.java:134)
    weblogic.jsp.internal.jsp.el.ExpressionEvaluatorImpl.evaluate(ExpressionEvaluatorImpl.java:125)
    Is it possible to switch the JSP / EL engine to Jasper? I'd expect some property pointing to ExpressionEvaluator implementation / parameter in the deployment descriptor but I haven't found anything like that yet.
    thanks
    Tomas

    Anyway I've achieved some progress with the Jasper - I've found that when precompiled using the JspC compiler from Jasper package, the resulting servlets are inherited from org.apache.jasper.runtime.HttpJspBase and thus should probably use the "proper" JSP EL implementation. But I still can't use these servlets from Weblogic, as I receive java.lang.NoClassDefFoundError: Could not initialize class org.apache.jasper.runtime.PageContextImpl.
    java.lang.NoClassDefFoundError: Could not initialize class org.apache.jasper.runtime.PageContextImpl
         at org.apache.jsp.WEB_002dINF.jsp.servletExceptionFragment_jsp._jspService(servletExceptionFragment_jsp.java:64)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
         at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
         at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
         at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
         at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
         at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:502)
         at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:251)
         at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:145)
         at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:251)
         at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1144)
         at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:880)
    The servlet is compiled properly, the jasper-runtime.jar is in the WEB-INF/lib directory, yet the weblogic is not able to load the PageContextImpl class :-(
    Edited by: user6510516 on 25.2.2009 4:14

  • Puzzled

    My company had a 3rd party develop a flash mini site that has had some issues with loading external swf files. When asked about it they said there is an issue with a flash movie loading any file with a capital letter in the name such as "BikeTire.swf" and suggested using all lower case letters. They also went further to say that the use of capital letters slows performance in a J2EE environment.
    I know that if an external swf file is being loaded into an empty movie clip or onto a level, that thet file names are case sensitive. I have never heard of this issue before. Can someone shine some light on this for me? Is the above statement true about importing external swf files?

    All things being equal, I would imagine that evaluating a string case-insensitive is more efficient than evaluating a string case-insensitive. The former will compare once for each byte whereas the latter has to both evaluate whether a letter is present and then also check the opposite case.
    However, I would be shocked if this in practice was an actual scaling bottleneck in the vast majority of systems.
    - Saish

  • ORA-06502 on  'SQL query' report with sort in 'Report Attributes'

    Hi All,
    We get the next error if we set sorting on a column in a 'Report' based on a 'SQL query'. Removing the sort, error disappeares:
    failed to parse SQL query:
    ORA-06502: PL/SQL: numeric or value error: NULL index table key value
    Any suggestions?
    Erik

    Erik,
    Thanks, this explains it. By specifying the request as part of your URL you run into the recently uncovered issue. The request you're setting is REMFROMLIST and ADD2LIST. You probably either have links that include those requests or you have branches where you specify them. Either way, in order to get reports sorting to work, you'll have to make sure that the request strings are not part of your URL. This is a work-around and the upcoming HTML DB patch release will solve this issue.
    One way of avoiding this is to have computations on the previous pages that set a napplication level or page level item to the REMFROMLIST and ADD2LIST values and then you can use those items for your conditions that are currently evaluating those strings.
    Hope this helps and sorry for the inconvenience,
    Marc

  • What is wrong with this?

    I am trying to make a program that does simple binary operations, it is not working. I think I am missing some constructors, but don't know what they are. Any help would be appreciated.
    //Expression.java
    package Math;
    public abstract class Expression {
         public abstract String toString();     
         public abstract double evaluateMe();
         public static void main(String args[]){
         Sum s1 = new Sum(new Number(7.123456789), new Number(11.3344));
         Sum s2 = new Sum(s1, new Multiply(s1, new Number(3)));
         System.out.println("s2 = " + s2 + " with value " + s2.evaluateMe());
    //Number.java
    package Math;
    public class Number extends Expression  {
      double num;
           public String toString() {
                  return String.valueOf(num);
           //return num.decimalFormat()
           //return the number but to 2nd place
      public double evaluateMe(){
           return num;
    //Sum.java
    package Math;
    public class Sum extends Expression {
         Expression left;
         Expression right;
         public String toString(){
              return "(" + left.toString() + ")" + "+" + "(" + right.toString() + ")";
         public double evaluateMe(){
              return left.evaluateMe() + right.evaluateMe();
    //Product.java
    package Math;
    public class Product extends Expression {
         Expression left;
         Expression right;
         public String toString(){
              return "(" + left.toString() + ")" + "*" + "(" + right.toString() + ")";
         public double evaluateMe(){
              return left.evaluateMe() * right.evaluateMe();
    }Once again Thanks

    HERE YOU GO!
    YOU OWE ME BIG!
    public class MathMachine{
    public static void main(String[] args){
         new MathMachine();
    public MathMachine(){
         Expression e1 = new Expression(Operation.ADD, 5, 3);
         Expression e2 = new Expression(Operation.MULTIPLY, new Number(2), e1);
         System.out.println("Expression: " + e2.toString() + " = " + e2.evaluate().getValue());
    // EVALUATOR
    public interface Evaluator{
    public String toString();
    public Number evaluate();
    // NUMBER
    public class Number implements Evaluator{
    public Number(double number){ this.number = number; }
    public String toString(){ return "" + number; }
    public Number evaluate(){ return this; }
    public double getValue(){ return number; }
         double number;
    // EXPRESSION
    public class Expression implements Evaluator{
    public Expression(int operation, double x, double y){
         this.operation = operation;
         this.x = new Number(x);
         this.y = new Number(y);
    public Expression(int operation, Evaluator x, Evaluator y){
         this.operation = operation;
         this.x = x;
         this.y = y;
    public String toString(){
         return "(" + x.toString() + Operation.getOperatorString(operation) + y.toString() + ")";
    public Number evaluate(){ return new Number(Operation.evaluate(this)); }
         int operation;
         Evaluator x;
         Evaluator y;
    // OPERATION
    public static class Operation{
         static final int ADD = 1;
         static final int SUBTRACT = 2;
         static final int MULTIPLY = 3;
         static final int DIVIDE = 4;
    public static String getOperatorString(int operator){
         switch(operator){
         case ADD: return "+";
         case SUBTRACT: return "-";
         case MULTIPLY: return "*";
         case DIVIDE: return "/";
         default: return "error";
    public static double evaluate(Expression e){
         switch(e.operation){
         case ADD: return e.x.evaluate().getValue() + e.y.evaluate().getValue();
         case SUBTRACT: return e.x.evaluate().getValue() - e.y.evaluate().getValue();
         case MULTIPLY: return e.x.evaluate().getValue() * e.y.evaluate().getValue();
         case DIVIDE: return e.x.evaluate().getValue() / e.y.evaluate().getValue();
         default: return Double.NaN;
    }

  • Multiple Expressions

    I'm trying to wrap my brain around some XPATH. I have two variables in a switch statement that I want to compare and take one of three paths..
    Path1: Both Are presnet
    Path 2/3: Either is present, but not the other.
    Here's my XPATH - my question is how do I evaluate BOTH of these statements in one expression?
    bpws:getVariableData('InvokePersonTokenOutVariable','payload','/ns6:getPersonTokenProcessResponse/ns6:personToken')!=''
    and
    bpws:getVariableData('InvokeCaseTokenOutputVariable','payload','/ns2:GetCaseTokenProcessResponse/ns2:CaseToken') !=''
    I tried using the AND operator and () in different ways, but it still breaks. Any ideas?
    thanks
    b

    Hi Brian,
    If I understand correctly, you are trying to evaluate NULL strings in your XPATH. If my assumtion is correct, then I must share that in my experience, evaluating NULL strings by - bpws:getVariableData('InvokePersonTokenOutVariable','payload','/ns6:getPersonTokenProcessResponse/ns6:personToken')!='' does not work properly.
    An alternative can be using the "string-length()" function and base your XPATH on the string length and not on the content when it comes to NULL String handling.
    If my assumption is not correct, then please ignore this post:)
    Regards,
    Nishant

  • Problem getting field names with OCI

    Hi,
    I am trying to retrieve the names of select fields through the
    OCI using OCIParamGet() followed by OCIAttrGet(). This seems to
    work OK, in most cases, except occasionally I get one field name
    concatenated to the following field name.
    Has anyone else seen this before, and if so, how do you get
    around it? Let me know if you need more details.
    Thanks in advance.
    Tim
    null

    That worked. Thanks!
    Peter Kls (guest) wrote:
    : Timothy Sim (guest) wrote:
    : : Hi,
    : : I am trying to retrieve the names of select fields through
    the
    : : OCI using OCIParamGet() followed by OCIAttrGet(). This seems
    to
    : : work OK, in most cases, except occasionally I get one field
    : name
    : : concatenated to the following field name.
    : Try evaluating the string length returned by the OCIAttrGet
    call.
    : The name string is not (always) \nul terminated.
    : : Thanks in advance.
    : : Tim
    : good luck
    : Peter
    null

Maybe you are looking for

  • Disk almost full

    How do I fix this? I have this message that keeps popping up that says, "Start up disk almost full." I have reset my cache in safari, deleted as many photos as I could, but it still says the same thing. What should I do? Thanks so much! Also, I looke

  • Bizarre permissions issue: Can't write to owned folders

    Has anyone experienced this and possibly has a fix ? I used Carbon Copy Cloner to duplicate a drive, and everything seems to be OK with the new drive (all the files are there and read properly), except I cannot write to any of the drive's subdirector

  • Contact Card Image - Including with new email

    I know I am not going crazy.... I could swear there was a way from within Mail (not .Mac) to include you "main contact image" on all outgoing mail. Is that feature not included any longer? If it is, where is that setting buried? Thanks for the help!

  • Jpegs continue to open in Camera raw

    I run CS5, after I  work my images up in camera raw, crop, color corrected, etc... and I save as a jpeg, it doesn't always hold the crop and then continues to automatically open in camera raw.  I was told once that meant that the images were not jpeg

  • How call a method from another class

    i make three class.class A,class B and class C. class A have One button. Class B have a action listener of that button. class c have a metod like public void test(){     } how can i call a method in class b from class c; is it necessary to pass the c