可能重复: 求字符串形式的数学表达式
我们的任务需要帮助。我试图创建一个程序,它将使用运算符优先级进行计算。如果可能的话,我想要计算数组中的表达式。为了前夫。4+2x2-3应先计算2x2,结果为4+4-3等。我的程序只计算第一个操作,但不能通过其他程序重复。还有..。它只计算最高优先级操作符在开头的时间。例如。2^1-2变为2-2.但是当2-1^2不做anything.thanks的帮助
List<String> subroutine = new CopyOnWriteArrayList<String>(input);
for(String i : subroutine)
{
switch(currentstate)
{
case q0:
if(isDigit(i))
{
currentstate = q1;
}
break;
case q1:
if(i.equals("^"))
{
maxPriority = i;
int index = subroutine.indexOf(maxPriority);
int num1 = Integer.parseInt(subroutine.get(index-1));
int num2 = Integer.parseInt(subroutine.get(index+1));
int total = (int) Math.pow(num1, num2);
String stringTotal = Integer.toString(total);
String addToExp = subroutine.set(index, stringTotal);
int indexAddToExp = subroutine.indexOf(stringTotal);
subroutine.remove(indexAddToExp+1);
subroutine.remove(indexAddToExp-1);
System.out.println(subroutine);
}
else if( (i.equals("x") || i.equals("/")) && (!input.contains("^")) )
{
if(i.equals("x"))
{
maxPriority = i;
int index = subroutine.indexOf(maxPriority);
int num1 = Integer.parseInt(subroutine.get(index-1));
int num2 = Integer.parseInt(subroutine.get(index+1));
int total = num1 * num2;
String stringTotal = Integer.toString(total);
String addToExp = subroutine.set(index, stringTotal);
int indexAddToExp = subroutine.indexOf(stringTotal);
subroutine.remove(indexAddToExp+1);
subroutine.remove(indexAddToExp-1);
}发布于 2012-10-12 12:11:25
您应该考虑构建一个比简单地使用字符串集合更复杂的表达式结构。
基本上,您需要根据给定的抽象语法树将给定的算术表达式解析为上下文自由文法,大致如下所示:
ArithmethicExpression := CompoundExpression | LiteralExpresion
LiteralExpression := {0-9}+ (meaning at least one digit)
CompoundExpression := LiteralExpression FunctionExpression LiteralExpression这个语法只是一个粗略的概念,你需要什么,但它肯定会帮助你更容易地实现你所需要的。
https://stackoverflow.com/questions/12858702
复制相似问题