可能重复:
评估以字符串形式给出的数学表达式
我需要一些帮助来完成我们的任务。我试图创建一个将使用运算符优先级进行计算的程序。如果可能的话,我想计算一个数组列表中的表达式。例如。[4+2x2-3] 应该首先计算 2x2,所以结果将是 [4+4-3] 等等......我的程序只计算第一个操作,但不能通过其他操作重复。也..它只计算最高优先级的运算符何时开始。前任。[2^1-2] 变为 [2-2]。但是当 [2-1^2] 它什么也没做。谢谢帮助
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);
}