rustock
rustock

Reputation: 397

How to calculate a arithmetic expression (String) and return the answer?

I know how to calculate easy expression without variables. But how to do, when in line we have expression with "x"? For example

(x+1)*(x-1)

In this example program should to return: x^2 - 1

Upvotes: 0

Views: 675

Answers (4)

Noorul
Noorul

Reputation: 3444

When we go to the interview they asking the this logical type of question. i to met the same problem. but i couldn't able to success the interview because this type of questions. Later i found the result of my own after i search in in the internet. Friends who are all want to do this..

follow this operation. i will give this full of free.

I will enter the equation as string Like.

a*b*c+d/m-x.

get this equation as string object. and use following functions.#

public void calc() throws IOException
{
    String equation,store,get;

    StringBuilder sb= new StringBuilder();
    DataInputStream dis= new DataInputStream(System.in);
    System.out.println("Enter the equation");
    equation= dis.readLine();
    equation="%"+equation+"%";
    byte[] buf= equation.getBytes();
    for(int i=0;i<equation.length();i++)
    {
        if(buf[i]>=97&&buf[i]<=122)
        {
            System.out.println("Enter the value for "+(char)buf[i]);
            get=dis.readLine();
            sb.append(get);
        }
        else
            sb.append((char)buf[i]);
    }
    store= sb.toString();

    char[] buf1= new char[25];

    for(int i=0;i<store.length();i++)
    {
        buf1[i]=store.charAt(i);          
    }
    for(int i=0;i<buf1.length;i++)
    {
        no.append(buf1[i]);
    }
    System.out.println(no.toString());
    int m,n=0;
    for(int i=0;i<no.length()-1;i++)
    {
        if('/'==no.charAt(i))
        {
            leftCount=rightCount=0;
            m=findLeftValue(i-1) / findRightValue(i+1);
            no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
            i=0;  
        }          
   }


    for(int i=0;i<no.length()-1;i++)
    {
        if('*'==no.charAt(i))
        {
            leftCount=rightCount=0;
            m=findLeftValue(i-1) * findRightValue(i+1);
            no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
            i=0;  
        }          
   }
    for(int i=0;i<no.length()-1;i++)
    {
        if('+'==no.charAt(i))
        {
            leftCount=rightCount=0;
            m=findLeftValue(i-1) + findRightValue(i+1);
            no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
            i=0;  
        }          
   } 
     for(int i=0;i<no.length()-1;i++)
    {
        if('-'==no.charAt(i))
        {
            leftCount=rightCount=0;
            m=findLeftValue(i-1) - findRightValue(i+1);
            no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
            i=0;                 
        }          
   }
    for(int i=0;i<no.length();i++)
    {
        if('%'==no.charAt(i))
        {
            no.deleteCharAt(i);
            i=0;
        }
    }
    System.out.println(no.toString());



}
public int findLeftValue(int i)
{
    StringBuilder sb= new StringBuilder();
    int x=0;
    while(no.charAt(i)!='*'&&no.charAt(i)!='+'&&no.charAt(i)!='-'&&no.charAt(i)!='/' &&no.charAt(i)!='%')
    {
          leftCount++;
          sb.insert(0, no.charAt(i));
          i--;
    }          
     x=Integer.parseInt(sb.toString());
    return x;
}
 public int findRightValue(int i)
{
    StringBuilder sb= new StringBuilder();
    int x;            
    while(no.charAt(i)!='*'&&no.charAt(i)!='+'&&no.charAt(i)!='-'&&no.charAt(i)!='/' &&no.charAt(i)!='%')
    {        
        rightCount++;
        sb.append(no.charAt(i));            
        i++;
    }     
    x=Integer.parseInt(sb.toString());
    return x;
}          

here may be unused variable may be there.please find and remove it. I didn't set any preferences to the calculation. just i made up with the flow. if you change the flow the answer will be different. so, Keep in mind. and you can do the same for different operators also. And One more thing is that, Please verify the equation before proceeding the function. because, it will not check whether the equation is correct or wrong.(a+*d++c). it is not correct equation. The equation should be correct format.. Like a+b*c-d/x.

Enjoy ..Break the interview and get your correct job..

Upvotes: -1

Alexander R&#252;hl
Alexander R&#252;hl

Reputation: 6939

What you are asking for, is letting a program transform (and possibly solve) mathematical equations. This is of course possible and there are tools and certainly APIs around which do it, but it's definitely beyond hacking a java program by your own.

In case you just like to calculate the result of a given formula, then this is doable. Interestingly, you can just throw an equation at Google (e.g. (5 + 3) * (8-4)) and it will give you the result. So, why not just use it? ;-)

Upvotes: 0

Quentin Proust
Quentin Proust

Reputation: 108

You might want to look at the scripting feature of java. It seems that you can execute Javascript (or other scripting languages) from Java using this scripting engine.

You will find some examples at https://today.java.net/pub/a/today/2006/04/11/scripting-for-java-platform.html.

Upvotes: 0

mprivat
mprivat

Reputation: 21912

It's a non-trivial endeavor. I would strongly suggest you look at what's out there. For example Symja

Upvotes: 4

Related Questions