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.

Similar Messages

  • Can you create an object from a string

    I have been working on creating a dynamic form, creating the
    form items from an xml file. I am getting very close to conquering
    this task. I will share it when it's complete.
    However, I am stuck at the moment trying to create an object
    from a string. For example, if the xml item is an HBox I want to
    create an HBox. Like this: parentObject = new arrayOfFormItems[
    index ]..type ()
    This isn't working. First, is this possible using some syntax
    I am unaware of in Flex? I don't want to use a large if or case
    statement if possible.
    Thanks in advance for your help!

    Thank you very much. Indeed that did solve the one problem. I
    missed the casting as a Display Object. That is awesome!
    I do still however, have to instantiate one of every item I
    want to dynamically create or I get the following error when I try
    to create a dynamic object that I have not instantiated before.
    ReferenceError: Error #1065: Variable HBox is not defined.
    at global/flash.utils::getDefinitionByName()
    at MyForm/buildForm()
    at DynamicForm/::onComplete()
    at
    flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/flash.net:URLLoader::onComplete()
    I read that you have no choice but to instantiate one of each
    type to force the linker to link the code for that class into the
    .swf. Unless you know another way to force it.
    This is what I have in my Application mxml to get it to work:
    <mx:HBox>
    <mx:Text visible="false"/>
    <mx:TextArea visible="false"/>
    <mx:TextInput visible="false"/>
    <mx:DateField visible="false"/>
    </mx:HBox>
    And those are the types I'm using to test with. . . I will
    have to add all the others I want to use as well . . .

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

  • Take and delete a String from another String

    I have original input string= 111100001111
    I need to Take for example the least 4 bits .... Output= 1111
    and to be removed from the original input string so the original input string= 11110000 
    I am trying to make a generic one but the point is that I can not delete subset that I take from the original input String.  
    How can I take and delete from a string in the same time? 
    Solved!
    Go to Solution.

    Something like this?
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Split String.png ‏13 KB

  • Solve equation with one unknown parameter (x)

    I am working on a Windows Phone program that calculates taxes due. One of the calculations is a formula/equation with an unknown 'x'. I have searched a lot on solving equations with vb but this really exceeds my - admittedly small - math knob. Perhaps you
    can help me out.
    The equation to solve is (for example):
    ((25000 + x) * 0.06) + x = 16500
    The only unknown variable is x. Does someone know the proper code to solve this equation?

    Are you looking to code some super-intelligent maths equation solver that can solve any type of equation (if so - good luck!)? Or are the equations you want to solve all of the same type?
    The example you gave is of the form (A + x) * B + x = C. You can rearrange that to (1 + B) * x + A * B = C and from there to x = (C - A * B) / (1 + B).
    If all your equations are in that form, you just need to identify the value of A, B and C and use the last formula I gave to calculate x.
    I wasn't going to do that for him.
    Let's see here, he's building a program for tax calculation and he can't do 8th grade algebra??
    Still lost in code, just at a little higher level.

  • Extracting data from a string of characters

    Hi,
    I have a problem that I am having difficulty solving, if anyone has any bright ideas it would be a great help.
    I have a description field in one of my tables and the description would read something like
    my website can be found at www.mywebsite.com, and it is great
    I want to be able to extract the web address from this sentance, so the result would be
    www.mywebsite.com
    I can do this specific for one sentance but I can't find a way to do it for many different sentances.
    cheers in advance

    If you're using 10g, you probably want to do something with regular expressions:
    SQL> with strings as (
      2    select
      3              'my website can be found at www.mywebsite.com, and it is great' str
      4    from
      5              dual
      6    union all
      7    select
      8              'my website can be found at WWW.myWebSite.com, and it is great'
      9    from
    10              dual
    11    union all
    12    select
    13              'our web address is www.mywebsite.co.uk' str
    14    from
    15              dual
    16    union all
    17    select
    18              'http://www.mywebsite.com/great'
    19    from
    20              dual)
    21  select
    22            s.str
    23          , regexp_substr(s.str, 'www\.[a-z0-9-\.?]*', 1, 1, 'i')  extr
    24  from
    25            strings s
    26  /
    STR                                                           EXTR
    my website can be found at www.mywebsite.com, and it is great www.mywebsite.com
    my website can be found at WWW.myWebSite.com, and it is great WWW.myWebSite.com
    our web address is www.mywebsite.co.uk                        www.mywebsite.co.uk
    http://www.mywebsite.com/great                                www.mywebsite.comYou'd be better asking this kind of thing on the PL/SQL (and definitely better asking someone other than me anything further about regular expressions!)

  • Read equations from word document programatically

    hi
    its too difficult to problem i think but soluation is there.
    i want to read equations from word document using java. i was tried in xml prser also ,there i can 't find the equation format.
    any body tell me how to extract equation from word .

    Everyone that has posted that you have 2 problems is absolutly correct, you will have to use some 3rd party product to read the file, or make your own MS-Word decoder--a task for which MS itself has problems doing reliably between versions. You could set up some DDE or OLE via Java/C and Excel... have fun it that is your choosen path, you'll want to talk to them in the JNI forum on how to get started there.
    As far as parsing, you have to be able to identify the formula, is it an Excel formula? If so, then you have to be able to copy the formula, it does not show as text in cells. If it is not a formula, but just text in a cell, then copy it into a String in Java.
    Now you have the String, use String.split or other tokenizer to break the String appart, and then you have to process the tokens. Nobody here is going to write the front end of an interpreter for you to process your sting into appropriat logic and tokens.
    The task you embark on is not one of triviality, but can be done. The real question is: "Is it really worth it to you?" Only you can answer that. If you need refernce material for parsing--look up discussions of language, compiler, and interpreter development--most of the ones I've run across have excellent discussions on parsing and tokenizing.

  • Replace a character from a string

    Hi,
    how can I replace a particular character from a string on a particular occurrence? Say for eg, if i wan to replace 'a' of second occurrence from 'abcabcabc', then what should i do? I guess the normal REPLACE function replaces every occurrence in a given string. So is there any other way to solve this?
    Thanks!

    If you are in 9i:
    Then you got to split the string into based on the nth position.
    SQL> select replace('abddefabc','a','x') from dual;
    REPLACE('
    xbddefxbc
    SQL> select instr('abddefabc','a',2) from dual;
    INSTR('ABDDEFABC','A',2)
                           7
    SQL> select substr('abddefabc',1,instr('abddefabc','a',2)-1),substr('abddefabc',instr('abddefabc','a',2)) from dual;
    SUBSTR SUB
    abddef abc
    SQL> select substr('abddefabc',1,instr('abddefabc','a',2)-1),replace(substr('abddefabc',instr('abddefabc','a',2)),'a','X') as replaced from dual;
    SUBSTR REP
    abddef XbcOfcourse, later on you can join the string..
    Jithendra

  • Replacing a set of characters from a string in oracle sql query

    I want to replace a set of characters ( ~    !     @    #     $     %     ^     *     /     \     +    :    ;    |     <     >     ?    _  ,) from a STRING in sql
    select 'TESTING ! ABC 123 #'
    FROM DUAL;
    What is the best way to do it? Please provide examples also.

    What is your expected output... The query I posted just removes them, it never replaces them with spaces..your string already has space.. if you want to remove space as well .. try this...
    SELECT TRANSLATE ('TESTING ! ABC 123 #', '-~!@#$%^*/\+:;|<>?_, ', ' ') FROM DUAL;
    Output:
    --TESTINGABC123
    Else post your expected output..
    Cheers,
    Manik.

  • Problems with Reflection API and intantiating an class from a string value

    I want to instantiate a class with the name from a String. I have used the reflection api so:
    static Object createObject(String className) {
    Object object = null;
    try {
    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    } catch (InstantiationException e) {
    System.out.println(e);
    } catch (IllegalAccessException e) {
    System.out.println(e);
    } catch (ClassNotFoundException e) {
    System.out.println(e);
    return object;
    Let's say my class name is "Frame1".
    and then if i use:
    Frame1 frm = (Frame1) createObject("Frame1");
    everything is ok but i cannot do this because the name "Frame1" is a String variable called "name" and it doesn't work like:
    name frm = (name) createObject("Frame1");
    where i'm i mistaking?
    Thanks very much!

    i have understood what you have told me but here is a little problem
    here is how my test code looks like
    Class[] parameterTypes = new Class[] {String.class};
    Object frm = createObject("Frame1");
    Class cls = frm.getClass();
    cls.getMethod("pack",parameterTypes);
    cls.getMethod("validate",parameterTypes);
    everything works ok till now.
    usually if i would of had instantiated the "Frame1" class standardly the "cls" (or "frm" in the first question ) object would be an java.awt.Window object so now i can't use the function (proprietary):
    frame_pos_size.frame_pos_size(frm,true);
    this function requires as parameters: frame_pos_size(java.awt.Window, boolean)
    because my cls or frm objects are not java.awt.Window i really don't find any solution for my problem. I hope you have understood my problem. Please help. Thanks a lot in advance.

  • How can i store values from my String into Array

    Hi guys
    i wants to store all the values from my string into an array,,,, after converting them into intergers,,,, how i can do this becs i have a peice of code which just give me a value of a character at time,,,,charat(2)...BUT i want to the values from String to store in an Array
    here is my peice of code which i m using for 1 char at time
    int[] ExampleArray2 = new int[24];
    String tempci = "Battle of Midway";
    for(int i=0;i>=tempci.length();i++)
    int ascii = tempci.charAt(i); //Get ascii value for the first character.

    public class d1
         public static final void main( String args[] )
              int[] ExampleArray2 = new int[24];
              String tempci = "Battle of Midway";
              for(int i=0;i<tempci.length();i++)
                   int ascii = tempci.charAt(i);
                   ExampleArray2=ascii;
              for(int i=0;i<ExampleArray2.length;i++)
                   System.out.println(ExampleArray2[i]);

  • Getting char values from a string problem

    Hi,
    Here's an example of what I'm trying to do:
    boolean loopSwitch = true;
    while (loopSwitch)
         String orderDecider = JOptionPane.showInputDialog (null, "Would you like your numbers to be ordered in   ascending or descending order(A/D)",      "Order decision", JOptionPane.QUESTION_MESSAGE);
         if (orderDecider == A)
         loopSwitch = false;
         }I basically want the user to input either a/A/d/D and to get the char values from the string so I can use them in an if statement.
    Basically, I wanna parse the string into a char.
    Is this possible?
    Thanks.
    Edited by: xcd on Oct 16, 2009 8:38 AM

    Why not just use the String.equals() method to compare a String to a String?
    But if you must, you can use the String.charAt() method to return a char at a particular location in the String.
    Note: char literals need to be surrounded by single quotes ('A') and String literals need to be surrounded by double quotes ("A").

  • Removing Null values from character string

    Hi All,
    Can i remove NULL values (hexadecimal - 0000) from character string. I am uploading a file from presentation layer (shared server) and getting NULL values in many fields which i want to remove.
    please assist.
    Thanks for you help..
    Regards,
    Mohaiyuddin

    Hi,
    Most likely, nobody needed it, but if anybody in future will need the solution for related problem  - here's solution:
    data: lv_nullchar type xstring value '0'.
    shift lv_xstring right deleting trailing lv_nullchar in byte mode.
    shift lv_xstring left deleting leading lv_nullchar in byte mode.
    This hack deleting null chars in lv_xstring at end file and at begining of file. Works perfect for me, where i also worked with files.

  • How to get the Values i need from a String???

    hi i need some help on my program,
    I have a Server that actually sent some data to my Client.
    The data consist of some messages and intergers . The whole piece of data is stores as a String message.
    ARRAY 'Monitor Chart' 2 5
    'Total OverFlow' 'Queued' 'Completed' 'Host Resets' 'Errors'''
    0.0 1.0 2.0 3.0 4.0
    'Series1' 11.0 0.6 8.6 11.5 6.6
    'Series2' 12.8 6.7 21.6 11.1 30.0Inside the Client i need to get the values out to showed on my textfields
    Example :
    Tf1 = 11.0
    Tf2 = 0.6
    Tf3 = 8.6
    Tf4 = 11.5
    Tf5 = 6.6
    Question: How to i get the values out from the String???

    using the split() method. i am able to split everything now
    so it appear somthing like this :
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class testing{
         String d1 =     "ARRAY 'Monitor Chart' 1 5";
         String d2 = "'Total OverFlow' 'Queued' 'Completed' 'Host Resets' 'Errors'";
         String d3 = "'' 0.0 1.0 2.0 3.0 4.0 ";
         String d4 = "'Series1' 11.0 0.6 8.6 11.5 6.6 ";
         String d5 = "'Series2' 12.8 6.7 21.6 11.1 30.0 ";
         String data = d1 + d2 + d3 + d4 + d5;     
         public testing(){
              System.out.println(data);
              String[] result = data.split("\\s");
              for(int x=0;x<result.length;x++)
              System.out.println(result[x]);
         public static void main (String args[])throws IOException{
            testing Application = new testing();
    }ARRAY
    'Monitor
    Chart'
    2
    5
    'Total OverFlow'
    'Queued'
    'Completed'
    'Host Resets'
    'Errors'''
    0.0
    1.0
    2.0
    3.0
    4.0
    'Series1'
    11.0
    0.6
    8.6
    11.5
    6.6
    'Series2'
    12.8
    6.7
    21.6
    11.1
    30.0
    but how do i get the values out ??how do i noe it is which index or wad?
    11.0
    0.6
    8.6
    11.5
    6.6

  • Escape single quote from a String variable

    Hi,
    I have a String variable called "name" which i am using in my form tag.
    <form name=test action="test.jsp?fname=<%=name%>" method="post">
    But i am getting Javascript error if the "name" variable contains a string with some special characters like single quote( ' ).
    Plz help me to escape this special char from my String variable.
    Thanks..

    You need to url-encode the value using the URLEncoder class.
    http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html
    For example:
    <form name=test action="test.jsp?fname=<%=URLEncoder.encode(name, "ISO-8859-1")%>" method="post">

Maybe you are looking for