码迷,mamicode.com
首页 > 其他好文 > 详细

四则运算--计应192--雷耀博

时间:2021-04-13 11:46:30      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:中缀表达式   eval   表达式   def   set   运算   ide   list   tor   

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Stack;

public class Eval {

private static double parsePostfix(List<String> postfix) {
for (int i = 0; i < postfix.size(); i++) {
String word = postfix.get(i);
if (Operator.isSymbol(word)) {
double n1 = Double.parseDouble(postfix.get(i - 1));
double n2 = Double.parseDouble(postfix.get(i - 2));
double result = 0;
Operator symbol = Operator.value(word);
switch (symbol) {
case ADD:
result = n1 + n2;
break;
case SUBTRACT:
result = n2 - n1;
break;
case MULTIPLY:
result = n1 * n2;
break;
case DIVIDE:
result = n2 / n1;
break;
default:
break;
}
postfix.set(i, String.valueOf(result));
postfix.remove(i - 1);
postfix.remove(i - 2);
break;
}
}
if (postfix.size() == 1) {
return Double.parseDouble(postfix.get(0));
}
return parsePostfix(postfix);
}

private static List<String> infix2Postfix(List<String> infix) {
List<String> postfix = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
for (String word : infix) {
if (Operator.isSymbol(word)) {
if (stack.empty()) {
stack.push(word);
} else {
Operator symbol1 = Operator.value(stack.peek());
Operator symbol2 = Operator.value(word);
if (symbol2 == Operator.CLOSE) {
while (!stack.empty()) {
String pop = stack.pop();

1.将四则运算串分割出中缀表达式
2.将中缀表达式转换为后缀表达式
3.对后缀表达式进行求值得出结果

四则运算--计应192--雷耀博

标签:中缀表达式   eval   表达式   def   set   运算   ide   list   tor   

原文地址:https://www.cnblogs.com/hnzj-jy192-JT/p/14646035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!