1

I have a string like: 2+4*4/2, the string can be longer or shorter, but in both cases I need to parse it and calculate the division and multiplication first before the addition and subtracting.

What I did was put the string into a string array then:

double answer = 0;
for(int i=0; i< array.length; i++) {
    if (array[i].equals(“+”)){
        answer = Double.parseDouble(array[i-1]) + Double.parseDouble(array[i+1]);
    }
}

But I need a way to detect multiplication and division and calculate them first and add the result to the rest of the string.

tckmn
  • 57,719
  • 27
  • 114
  • 156
fullmoon
  • 8,030
  • 5
  • 43
  • 58
  • Are the double quotes in `“+”` just for illustrating? – Maroun Jun 16 '13 at 19:58
  • 2
    its something like this ?? [Similar Question](http://stackoverflow.com/questions/2605032/using-eval-in-java) or do you want to write your own ?? – DarthCoder Jun 16 '13 at 19:58
  • 1
    http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – zmbq Jun 16 '13 at 20:01
  • JAVA follows BODMAS notation during calculation. I cannot understand much from your question. But there are Tonnes of answers around it., http://stackoverflow.com/questions/5338122/arithmetic-operators-in-java-beginner-question – sathish_at_madison Jun 16 '13 at 20:01

2 Answers2

2

I have created demo program , this will help to resolve your query :

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class CalculatingString
{
    public static void main(String[] args)
    {
        String string="2323*1212-3434+12*200/2";
        System.out.println("Result : "+getAnswer(string));
    }

    private static List<Character> getSymbols(String string)
    {
        List<Character> listOfSymbols=new LinkedList<Character>(); 
        for(int i=0;i<string.length();i++)
        {
            char symbol=string.charAt(i);

            if(symbol=='-' || symbol=='+' || symbol=='*' || symbol=='/')
            {
                listOfSymbols.add(symbol);
            }
        }
        return listOfSymbols;
    }

    private static List<String> getOperands(String string)
    {
        String[] operandsArray=string.split("-|\\+|\\*|\\/");
        List<String> listOfOperands=new LinkedList<String>();

        for(int i=0;i<operandsArray.length;i++)
            listOfOperands.add(operandsArray[i]);

        return listOfOperands;
    }

    private static void listUpdater(List<Character> listOfSymbols,List<String> listOfOperands,int position,float result)
    {
        listOfSymbols.remove(position);
        listOfOperands.remove(position);
        listOfOperands.remove(position);
        listOfOperands.add(position,String.valueOf(result));
        //System.out.println("===========================================================================");
    }

    private static float getAnswer(String string)
    {
        List<Character> listOfSymbols=getSymbols(string);
        List<String> listOfOperands=getOperands(string);
        int operationCount=listOfSymbols.size();
        float operand1=0.0F;
        float operand2=0.0F;
        float result=0.0F;

        while(operationCount>0)
        {
            if(listOfSymbols.contains('*') || listOfSymbols.contains('/'))
            {
                int currentPositionMultiplication=listOfSymbols.indexOf('*');
                int currentPositionDividation=listOfSymbols.indexOf('/');

                if((currentPositionMultiplication<currentPositionDividation && currentPositionMultiplication!=-1) || currentPositionDividation==-1)
                {
                    operand1=Float.parseFloat(listOfOperands.get(currentPositionMultiplication));
                    operand2=Float.parseFloat(listOfOperands.get(currentPositionMultiplication+1));
                    result=operand1*operand2;

                    listUpdater(listOfSymbols,listOfOperands,currentPositionMultiplication,result);
                }
                else if((currentPositionMultiplication>currentPositionDividation && currentPositionDividation!=-1) || currentPositionMultiplication==-1)
                {
                    operand1=Float.parseFloat(listOfOperands.get(currentPositionDividation));
                    operand2=Float.parseFloat(listOfOperands.get(currentPositionDividation+1));
                    result=operand1/operand2;

                    listUpdater(listOfSymbols,listOfOperands,currentPositionDividation,result);
                }

            }
            else if(listOfSymbols.contains('-') || listOfSymbols.contains('+'))
            {
                int currentPositionSubstraction=listOfSymbols.indexOf('-');
                int currentPositionAddition=listOfSymbols.indexOf('+');

                if((currentPositionSubstraction<currentPositionAddition && currentPositionSubstraction!=-1) || currentPositionAddition==-1)
                {
                    operand1=Float.parseFloat(listOfOperands.get(currentPositionSubstraction));
                    operand2=Float.parseFloat(listOfOperands.get(currentPositionSubstraction+1));
                    result=operand1-operand2;

                    listUpdater(listOfSymbols,listOfOperands,currentPositionSubstraction,result);
                }
                else if((currentPositionSubstraction>currentPositionAddition && currentPositionAddition!=-1) || currentPositionSubstraction==-1)
                {

                    operand1=Float.parseFloat(listOfOperands.get(currentPositionAddition));
                    operand2=Float.parseFloat(listOfOperands.get(currentPositionAddition+1));
                    result=operand1+operand2;

                    listUpdater(listOfSymbols,listOfOperands,currentPositionAddition,result);
                }

            }
            operationCount--;
        }

        Iterator<String> iterator=listOfOperands.iterator(); 

        String finalResult="";

        while(iterator.hasNext())
        {
            finalResult=iterator.next();
        }

        return Float.parseFloat(finalResult);
    }
}
Ravi Jiyani
  • 919
  • 1
  • 10
  • 26
0

You need to convert your string into postfix notation. Details about it here: http://en.wikipedia.org/wiki/Reverse_Polish_notation

Hints for implementation: You need an stack for operators. You parse your string and every time you find an operand you copy it in the postfixed string. If you find an operator, you pop from the stack every operator with greater or equal priority, copy them in your new string and then push the actual operator.

After that you have to do the actual math and you need to use an operand stack. While parsing the string in the postfix notation, if you get an operand (number), you push it on the stack. If you get an operator, you take the last 2 elements on the stack and then put back the result of those two with the operator you're on.

Sorin
  • 908
  • 2
  • 8
  • 19