import
java.util.ArrayList;
import
java.util.HashMap;
import
java.util.List;
import
java.util.Map;
import
java.util.Stack;
import
java.util.StringTokenizer;
public
class
Calculator {
public
static
Double evaluate(String expression) {
Map<String,Integer> weight =
new
HashMap<String,Integer>();
weight.put(
"+"
,
1
);
weight.put(
"-"
,
1
);
weight.put(
"*"
,
2
);
weight.put(
"/"
,
2
);
List<String> postfix =
new
ArrayList<String>();
StringTokenizer tokenizer =
new
StringTokenizer(expression,
" "
);
Stack<String> stack =
new
Stack<String>();
while
(tokenizer.hasMoreElements()) {
String token =tokenizer.nextToken();
if
(token.equals(
"+"
) || token.equals(
"-"
) || token.equals(
"*"
) || token.equals(
"/"
)) {
while
(!stack.isEmpty() && weight.get(token) <= weight.get(stack.peek())) {
postfix.add(stack.pop());
}
stack.push(token);
}
else
{
postfix.add(token);
}
}
while
(!stack.isEmpty()) {
postfix.add(stack.pop());
}
for
(String str : postfix) {
if
(str.equals(
"+"
) || str.equals(
"-"
) || str.equals(
"*"
) || str.equals(
"/"
)) {
if
(str.equals(
"+"
)) {
stack.push(String.valueOf(Double.parseDouble(stack.pop())+Double.parseDouble(stack.pop())));
}
else
if
(str.equals(
"-"
)){
double
temp = Double.parseDouble(stack.pop());
stack.push(String.valueOf(Double.parseDouble(stack.pop())-temp));
}
else
if
(str.equals(
"*"
)){
stack.push(String.valueOf(Double.parseDouble(stack.pop())*Double.parseDouble(stack.pop())));
}
else
{
double
temp = Double.parseDouble(stack.pop());
stack.push(String.valueOf(Double.parseDouble(stack.pop())/temp));
}
}
else
{
stack.push(str);
}
}
return
Double.parseDouble(stack.pop());
}
}