Parsing an equation within a string

Well my friend and i are making a calculator which has the ability to take a String (the equation) and format it for calculation using the order of operations (PEMDAS).
What we have so far is it reads the equation from a textbox and passes the string to our prcoess void which atm looks like this:
    public static void process(String s){
        textfield_rawLine.setText("");
        s = s.trim().toLowerCase();
        String ans = String.valueOf(partAnswer);
        BasicOps.textfield_Answer.setText(ans);
    }the float variable partAnswer was left over from something else i tried ealier. We want to handle the numbers as floats for more accurate precision. At the moment we can handle simple equations, 4 + 3 etc, but not more complex such as (4 + 3) - (6 * 4) etc. Any ideas how we can accomplish what we need?

the generally accepted way is to convert the infix notation (4 + 3) into postfix notation (4 3 +) and then use a simple stack based processor to perform the math. The infix to postfix transformation, while not brain-dead simple, isn't particularly hard, either. There are probably loads of samples on the net.

Similar Messages

  • How to parse an equation?

    Here's my problem:
    The user enters an equation into a TextField. The app reads the TextField and records the equation into a String.
    Say the user enters 3x + 5. Now, I need to convert the String into an algorithm that will be able to calculate the value of 3x + 5 for any x.
    It might sound simple for 3x + 5, but consider an equation like this:
    (sin(x)^2 * 3cos(x)) / (e^(tan(x)) * sinh(4x) - x^x^x^345.55)
    How would I parse something like that?

    Well, I looked at the source code, and it uses several
    dozen classes with some kind of nodes and so forth
    I need something simple. Effective, but simple.
    The programme I am writing will be working as an
    applet, so I wouldn't want to have people first
    download Jep, then run the applet ...Just how simple is your "simple"?
    Every mathematical formula parser requires nodes and stuff to represent the equation in a tree and so forth; you'd be re-writing all that and that is effectively much more complex than just using a parser that is there. You don't have to know how or why JEP works to use it.
    JEP is fairly simple to use... did happen to you see the sample applet and its source?
    http://jep.sourceforge.net/sampleapplet.htm
    what about the usage doc: http://jep.sourceforge.net/doc_usage.htm
    Doesn't seem that complex to me... but if you really want to build a parser of your own, be my guest... btw, if you're into that, I know a great open source expression parser from which you might want to pick ideas! :)

  • Solving equations from a String

    How could I could a value from a String(lets say the value is"1+1"), then convert this value to a double, and solve it so that the result is 2?
    I tried this but it did not work:
    double equation = Double.parseDouble((resultField.getText()));
    double result = Math.abs(equation);
    resultField.setText(String.valueOf(result));

    By the way, if this is a homework assignment (say, to take a string holding a mathematical expression, and then parse the string and evaluate the resulting expression), then just delegating to a scripting language will probably be a fail.
    If it's not a homework assignment...then you can probably google for a mathematical library for Java and get another reasonable solution. Which you choose depends a lot on why you're doing this.

  • Findind out the number of lines within a string - using buffered reader

    Hi All,
    Want to know the number of lines within a string..Sample code is there for reference..could u help me out how to have the number of lines in a string without java comments (i.e string within /**------*/ and // should be eliminated)
    public class ReadLines {
         public static void main(String[] args) throws Exception{
              ReadLines rl = new ReadLines();
              rl.readLines();
         void readLines() throws Exception{
              String str = "/** This is a test message\n"+
                   "* for testing\n"+
                   "*/\n"+
                   "import java.io.*\n"+
                   "// this is again comment\n"+
                   "public class ReadLines {\n"+
              BufferedReader reader = new BufferedReader(new StringReader(str));
              String line = "";
              int count = 0;
              while ((line = reader.readLine())!= null )
                   //line = reader.readLine();
                   count++;
              System.out.println(count);
    }Thanks
    MK

    Hi
    What you need to do is parse the file in such a way that you read /*, */ and // as tokens. By that I mean rather than read a line at a time (although I'm sure you could), read it character by character. So every time you reach a new line character then increment the counter. But there are two casaes when you don increment the counter they are:
    If you encounter a / followed by * then keep reading but if you encounter a newline character then DONT increment the counter ONLY continue counting when you read a * followed by a / (as this is the end of the comment)
    If you encounter / followed by another / then do not count that particular line and go to the next line and continue counting from there.
    Where I've written 'continue counting' this is subject to the lines that follow not conforming to the above two cases.
    I hope this helps.

  • Process Message failed: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.

    Hi
    I am trying to process an X12 message and I am getting following error.
    Method : ProcessMessage
    Message : Process Message failed: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
    Parameter name: length
       at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
       at Q.Inbound.X12Preprocessor.getTranTypeFromFuncCode()
       at Q.Inbound.X12Preprocessor.setProcessType()
       at Q.Inbound.X12Preprocessor.getFuncGroupHeader(StreamReader sr)
       at Q.Inbound.X12Preprocessor.ProcessMessage(X12Definition& docInfo)
    Please help.
    Thanks

    Might try them over here.
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=csharpgeneral%2Cvbgeneral%2Cvcgeneral&filter=alltypes&sort=lastpostdesc
    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows]
    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees , and confers no rights.

  • [JS - CS3]  Can't REPLACE A with B within a string? Help Please...

    Hello Experts,
    First off - I'm a newbee to all this JS and especially with CS3.
    I have a string: '
    b myDocumentName
    which can have it's value as: '
    b 00000en_ Generator WX/WY
    Problem is, backshlashes ( / )are a bad thing for me...
    b Question:
    How can I do a 'replace' operation to replace the '/' from the string with a '_'?
    I have at the moment:
    > var myDocSaveName = oneResult[3]+oneResult[4]+oneResult[5];
    > myDocSaveName.replace(what "/", with "");
    > myDoc.save ("C:/DATA/"+myDocSaveName, undefined, undefined, true)
    I get an error Nr. 25... Offending text:"/"
    What am I doing wrong?

    'what' and 'with' are the names of those arguments. They should not be included in the statement:
    myDocSaveName.replace("/", "");
    But that still won't work because replace doesn't operate on a string in situ, it returns the modified string. So:
    myDocSaveName = myDocSaveName.replace("/", "");
    This too has its limitations. It'll change only the first instance of "/", not all of them. To change all of them, you need to restate the 'what' as a RegExp:
    myDocSaveName = myDocSaveName.replace(/\//g, "_");
    A RegExp literal is delimited by the "/" character, so to have it, alone, as the character to be sought you must use the backslash to escape the character. Then, to indicate you want the replace to happen globally within the string, you add the 'g' after the RegExp.
    Dave

  • How to get a set of character within a string?

    Hi,
    I need to cut a set of character within a string. I have tried everthing but I need help.
    Example.
    Database Version 11.2.0.3
    create table tst_string (message varchar2(600));
    insert into tst_string values ('ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)');
    insert into  tst_string values ('ANE4175I Starting Full VM restore of VMware Virtual Machine ''mfujiwara'' target node name=''VC1_DC1'', data mover node name=''VC1_DC1_DM3''  (SESSION: 3780)');
    commit;
    select * from tst_string;
    MESSAGE
    ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)
    ANE4175I Starting Full VM restore of VMware Virtual Machine 'mfujiwara' target node name='VC1_DC1', data mover node name='VC1_DC1_DM3'  (SESSION: 3780)
    ## I want get
    # From first line following values:
    node OSOGBO
    filespace OSOGBO\SystemState
    examined 43
    deleted 43
    retrying 0
    failed 0
    # From second line
    mfujiwara
    VC1_DC1
    VC1_DC1_DM3Any help can be useful...
    Thanks in advance.

    Hi Frank,
    It looks like message can be seen as delimited lsit of sub-messages, where a number of different characters (perhaps ',' amd ':') may serve as delimiters. Each sub-message may or consist (entirely or in part) of something you want to display.Yes. In my first case where is "ANR0166I" I want get the characteres before "," (e.g "OSOGBO," I want get "OSOGBO") excluding "(SESSION: 1506, PROCESS: 2)"
    Would a user-define PL/SQL function be okay for you?Yes.. no problem.
    I'm not good with shell script, but will try show what I want using SHELL commands:
    See this example:
    ### I create a file named "tst_string"
    $ vi tst_string
    ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState\NULL\System State\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)
    ## So I used a function sed to get my desired values. The command bellow is poor, but My point is the result.
    $ cat tst_string | sed 's/ANR0166I.*node //g' | sed 's/, filespace//g' | sed 's/, copygroup BACKUP and object type GROUP BASE with processing statistics: //g' | sed 's/. (SESSION.*//g' | sed 's/, deleted//g' | sed 's/, retrying//g' | sed 's/, and failed//g'
    OSOGBO OSOGBO\SystemState\NULL\System State\SystemState 43 43 0 0The result was:
    NODE     FILESPACE                              Examined     Deleted     Retrying        Failed      
    OSOGBO      OSOGBO\SystemState\NULL\System State\SystemState     43           43      0           0I will go check the links wich you mentioned.
    Thanks

  • Parseing a Float from a string.

    Does anyone know how to parse a float from a string variable? The documentation says there is a method for it, it doesn't say what it is(?).
    I.e. the equavilent of int this_num.parseint(this_string) only for a float.
    Thanks.

    Thanks, that helped...now for another apparently stupid question....
    How do you add two floats??
    I have:
    fInvAmount = fInvAmount + Float.parseFloat(rsSmartStreamInvoice.getString("invoice_amt"))
    and it tells me that 'operator + cannot be applied to java.lang.Float,float'

  • Finding a word within a string

    Hey everyone,
    Just having a little trouble with something.
    I'm trying to find a word -- that is, not a substring, an actual word as defined by the english language -- within a string.
    For example I don't want "hell" to be found in "hello".. only "hello" to be found.
    Currently i've got two strings, one is the sentance (String input), and one is the word to be found in the sentance (String word). I need the program to find the WORD, and then go back and search for the word again and again and again until it reaches the end of the string.
    This is what I've got thus far:
              for(i = 0; i < input.length(); i++)
                   // This statement checks the string "input" for the string "word" starting at offset 0 (as this is what the variable was first defined as)
                   if(input.indexOf(word, offset) >= 0)
                        // If it finds the word at all, this line increases the offset ahead of this word so it doesn't simply find the same word again
                        offset = offset + (input.indexOf(word)) + (word.length());
                        times++;
              }At the moment this searches for the sub-string, not the WORD which is what I would like it to do.
    What's the easiest way of going about this? I've been fiddling around trying to add extra sections to the if statement, for example
    if((input.indexOf(word, offset) >= 0) && (input.charAt(offset +1) == 32))(32 as in the ASCII character for a space, which would do what I wanted it to do)
    But I eventually get errors because at some stage or another the charAt is going to be higher than the actual length of the String. Plus, this only looks if there's a space next to the word - a word can be valid if it has a ! next to it for example, or a comma...
    Thanks for any help :)
    viddy

    I think there's a word boundary marker in regex. So it'd be "\\w+hello\\w+" or whatever the marker is, to be used with a Pattern instance.

  • Searching for a substring within a string

    can someone reccomend a simple way to search for a substring within a string and count the number occurences of that substring.
    The substring and the string will be provided as command line parameters.
    Thanks
    gg

    A simple way would be to use the indexOf methods in String:
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
    Not sure what this has to do with event handling though :-P

  • Get number of character within a String by number of pixels

    How can i get the number of character within a String
    by a width value...
    for example..
    i have a String = "1234567890abcdefghi.........."
    and when i give the width "10"
    i will get the String "12".
    or the number of charcter..
    or somthingggggggggggggggg
    please help..
    Shay

    i solved this...
    by doing somthing similar..
    i made a for loop on all character
    and evrey time i am get a sub string from the 0 till the loop index..
    and i am chashing the last string
    so when a sub width is greater the the requested width
    i am returning the lst cashed result
    thanks.. all..

  • Increment a number within a string

    Hi!
    How can I increment a number within a string ?
    This code doesn' t provide the rigth result
    DATA zahl TYPE I.
    DO 10 TIMES.
    zahl = zahl +  1.
    write:/ 'HALLO zahl'.
    ENDDO.

    Hello,
    Change the code like this.
    DATA ZAHL TYPE I.
    DATA: LV_ZAHL(8),
          CHAR(255).
    DO 10 TIMES.
      ZAHL = ZAHL + 1.
      WRITE: ZAHL TO LV_ZAHL.
      CONCATENATE 'HALLO' LV_ZAHL INTO CHAR.
      CONDENSE CHAR NO-GAPS.
      WRITE:/ CHAR."'HALLO'NO-GAP,ZAHL NO-GAP.
    ENDDO.
    Regards,
    Vasanth

  • OBIEE - Find position of the last occurrence of a charcter within a string.

    Hi,
    I have a requirement in 11.1.1.6.9 to be locate the position of the last occurrence of a character within a string.
    i.e. Given the following, I would want to locate the last "/":
    This/is/an/exampleI would like to return a value of 11. Now, there could be any number of "/" so I can't always locate the nth one - it must be the last one.
    Anyone any ideas?
    Thanks,
    John

    Your requirement is not complete. just in case you want to extract the last part 'example' just use substring and replace to trim up to required part.
    You may have to go for the same for multiple times.
    ETL is the best to handle this than BI.
    BTW: Check this How to use locate function if multiple occurences of same character
    Edited by: Srini VEERAVALLI on May 10, 2013 10:25 AM
    Good that given link is helped you to solve it ;)
    Edited by: Srini VEERAVALLI on May 13, 2013 7:47 AM

  • Separating character and number within the string

    I want to separate the character and the number within one string.
    For example,
    12345ABCD (the numbers and character may differ in lengths)
    I want to separate into two different string of 12435 and ABCD.
    Your help would be greatly appreciated.
    Thanks!

    here is an example:
    sample_separator.sql
    declare
      i        number := 0;
      j        number := 0;
      x        number := 0;
      vBasis   Varchar2(40) := '12345ABCD';
      vString1 Varchar2(40);
      vString2 Varchar2(40);
    begin
      for x in 1 .. length(vBasis) loop
        for i in 0 .. 9 loop
          if substr(vBasis,x,1) = to_char(i) then     
            vString1 := vString1 || substr(vBasis,x,1);
          end if;
        end loop;
        for j in 65 .. 90 loop
          if substr(vBasis,x,1) = chr(j) then
            vString2 := vString2 || substr(vBasis,x,1);
          end if;
        end loop;   
      end loop;
      dbms_output.put_line('vString1: '||vString1);
      dbms_output.put_line('vString2: '||vString2);
    end;
    /when run:
    SQL> @r:\sample_separator.sql;
    vString1: 12345
    vString2: ABCD
    PL/SQL procedure successfully completed.
    SQL> hope this helps.

  • Finding a pattern within a String

    How can I find a pattern within a string using Java? does Java has the ability to do this or do I have to write a function?

    The String API documentation shows how to do it.

Maybe you are looking for

  • Beta: Support for more languages

    We've added support for many more languages.  See the full list below.  You can access the beta by clicking this special link.  This link will allow you to use the site, same as before, but will also enable the new language support.  You can find add

  • Cannot load template

    When I open a page to update it content the loading is very slow. It took 5 min. to sync the template and open the page. The result is a page without the template in it. If I create a page from a blank template it's OK. I reinstalled Contribute and r

  • Need how to for deleting a snippet using a Mac

    I tried to follow the steps posted on 12/12/2007 by ThinkInk but need more detail. Thank you very much!

  • Microsoft Patch for OWA 2007 CRES Secure Mail Recipients

    CRES Secure Envelope Recipients attempting to open the CRES Secure Envelope through Microsoft OWA 2007 will need to enable the server side administrative option to disable the HTML/XML filter. Though this HTML filter option will be officially release

  • Want to upgrade RAM on 2011 Macbook pro 13 2.3GHz i5 4GB

    Hello all, First of all let me thanks you guys for the support you have been giving here. I am new to the forum and this is my first post, I recently bought the new 2011 Macbook pro 13inch 2.3GHz Dual-core Intel Core i5 with the 4GB RAM (4GB 1333MHz