Possible Duplicate:
Evaluating a math expression given in string form
i need some help in our assignment. im trying to create a program that will compute using operator precedence. if it is possible, i want to compute the expression inside an arraylist. for ex. [4+2x2-3] should calculate 2x2 first so the result will be [4+4-3] and so on... my program only calculates the first operation but couldn't reiterate through others. also.. it only calculates when the highest priority operator is in the beginning. ex. [2^1-2] becomes [2-2]. but when [2-1^2] it doesn't do anything.thanks for help
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);
}