Problem:
Smart Calculator

Your task is to write a program which reads an expression and evaluates it.

The expression consists of numerical values, operators and parentheses, and the ends with '='.

The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division.

Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right.

You may assume that there is no division by zero.

All calculation is performed as integers, and after the decimal point should be truncated

Length of the expression will not exceed 100.

-1 × 109 ≤ intermediate results of computation ≤ 109

Input

The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression.

Output

For each datasets, prints the result of calculation.

Sample Input

2
4-2*3=
4*(8+4+3)=

Output for the Sample Input

-2
60

Solution in JAVA (judge verdict: Accepted)

import java.util.*;

public class Main{
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();

		while(n-- > 0){
			p = sc.next().toCharArray();
			Parsed ans = expr(0);
			System.out.println(ans.val);
		}
	}

	static char[] p;

	static Parsed expr(int idx){
		Parsed r = term(idx);
		while(p[r.idx] == '+' || p[r.idx] == '-'){
			char op = p[r.idx];
			int tmp = r.val;
			r = term(r.idx + 1);
			if(op == '+') r.val = tmp + r.val;
			else r.val = tmp - r.val;
		}
		return r;
	}

	static Parsed term(int idx){
		Parsed r = fact(idx);
		while(p[r.idx] == '*' || p[r.idx] == '/'){
			char op = p[r.idx];
			int tmp = r.val;
			r = fact(r.idx + 1);
			if(op == '*') r.val = tmp * r.val;
			else r.val = tmp / r.val;
		}
		return r;
	}

	static Parsed fact(int idx){
		if(Character.isDigit(p[idx])){
			int t = p[idx++] - '0';
			while(Character.isDigit(p[idx]))t = t*10 + p[idx++] - '0';
			return new Parsed(t,idx);
		}
		else if(p[idx] == '('){
			Parsed r = expr(idx + 1);
			if(p[r.idx] != ')') return null;
			return new Parsed(r.val, r.idx + 1);
		}
		else return null;
	}
}

class Parsed{
	int val;
	int idx;
	Parsed(int val,int idx){
		this.val = val;
		this.idx = idx;
	}
}