解析字符串以计算数字

时间:2013-06-16 19:55:25

标签: java android

我有一个字符串:2+4*4/2,字符串可以更长或更短,但在这两种情况下我都需要解析它并在加法和减法之前先计算除法和乘法。

我所做的是将字符串放入字符串数组中,然后:

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]);
    }
}

但是我需要一种方法来检测乘法和除法并首先计算它们并将结果添加到字符串的其余部分。

2 个答案:

答案 0 :(得分:1)

我已经创建了演示程序,这将有助于解决您的查询:

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);
    }
}

答案 1 :(得分:0)

您需要将字符串转换为后缀表示法。有关它的详细信息:http://en.wikipedia.org/wiki/Reverse_Polish_notation

实施提示:您需要为运营商提供堆栈。您解析字符串,每次找到操作数时,都会将其复制到后缀字符串中。如果找到一个操作符,则从堆栈中弹出优先级更高或相等的每个操作符,将它们复制到新字符串中,然后按实际操作符。

之后你必须做实际的数学运算,你需要使用一个操作数堆栈。在使用后缀表示法解析字符串时,如果获得操作数(数字),则将其推入堆栈。如果你得到一个操作符,你可以获取堆栈中的最后两个元素,然后将这两个元素的结果与你所在的操作符一起放回。