Java实现中序表达式的实例代码

时间:2022-11-17 22:14:48

什么是中序表达式

前序(前缀)表达式要求每一个操作符出现在其操作数之前.一般不用. 写表达式的后序表达式一般是为了便利于计算机编程中栈的实现,所以用的较多.

具体代码如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package 表达式求值;
import java.util.stack;
/*
 * 中序表达式求值实现
 */
public class centerexpression {
 public double evaluate(string expression){ //传入中序表达式
  char [] ex = expression.tochararray();
  stack<double> num = new stack<>();
  stack<character> ops = new stack<>();
  for(int i = 0; i < ex.length; i++){  //循环将表达式依次入栈
   char c = ex[i];
   if(c < '9' && c > '0'){
    num.push(double.parsedouble(character.tostring(c)));
   }
   else if(c == '('){
    ops.push('(');
   }
   else if(c == ')'){
    while(true){
     char op = ops.pop();
     if(op == '('){
      break;
     }
     else{
      switch(op){
      case '+':num.push(num.pop()+num.pop());break;
      case '-':num.push(num.pop()-num.pop());break;
      case '*':num.push(num.pop()*num.pop());break;
      case '/':num.push(num.pop()/num.pop());break;
      default:break;
      }
     }
    }
   }
   else if(ops.empty() && (c == '+' || c == '-' || c == '*' || c == '/')){
    ops.push(c);
   }
   else if(!ops.isempty() && (c == '+' || c == '-' || c == '*' || c == '/')){
    char op =ops.peek();
    while((op == '*' || op == '/') && (c == '+' || c == '-')){
     op = ops.pop();
     switch(op){
     case '+':num.push(num.pop()+num.pop());break;
     case '-':num.push(num.pop()-num.pop());break;
     case '*':num.push(num.pop()*num.pop());break;
     case '/':num.push(num.pop()/num.pop());break;
     default:break;
     }
     if(ops.isempty()){
      break;
     }
     else{
      op = ops.peek();
     }
    }
    ops.push(c);
   }
  }
  while(!ops.isempty()){  //处理剩余可以按计算机扫描顺序处理的表达式
   char op =ops.pop();
   switch(op){
   case '+':num.push(num.pop()+num.pop());break;
   case '-':num.push(num.pop()-num.pop());break;
   case '*':num.push(num.pop()*num.pop());break;
   case '/':num.push(num.pop()/num.pop());break;
   default:break;
   }
  }
  return num.pop();
 }
 public static void main(string [] args){
  centerexpression exp = new centerexpression();
  system.out.println(exp.evaluate("1*2+5*3"));
 }
}

总结

以上所述是小编给大家介绍的java实现中序表达式的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://www.cnblogs.com/libin-blogs/archive/2018/08/08/9441231.html