1

我有一个类似: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]);
    }
}

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

4

2 回答 2

2

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

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);
    }
}
于 2015-01-14T04:10:19.577 回答
0

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

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

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

于 2013-06-16T20:02:13.617 回答