400-700-1307

Java计算器核心算法代码实现

2019-01-26 14:41

在进行一个表达式的计算时,先将表达式分割成数字和字符串然后利用出入栈将分割后的表达式进行中缀转后缀,再将后缀表达式进行计算得到结果(思想在上一篇写过)现在贴下Java语言的代码实现。(学习Java时间不长所以可能会有很多不足的地方,我会改进也欢迎大神可以给我一些意见和建议~谢谢啦)

我将这部分分成三个方法完成功能,并在getResult方法调用(getResult方法被主方法调用)

 
1
2
3
4
5
6
7
8
9
private String getResult(String str) {
    //分割
    String[] Str = segment(str);
    //中缀转后缀
    String newStr = infToSuf(Str);
    //后缀计算
    String result = sufToRes(newStr);
    return sufToRes(result);
  }

1.字符串分割,为避免在TextView上显示带空格删除时不方便而且显示屏就那么大占地方,录入时的字符串中没有空格然后就手动分割了

 
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
private static String[] segment(String str) {
    String[] exp = new String[str.length()+1];
    //找最近的索引并截取字符串
    int l = str.length();
    for(int i = 0;i < l+1;i++) {
      int index;
      int[] ind = new int[6];
      ind[0] = str.indexOf('+');
      ind[1] = str.indexOf('-');
      ind[2] = str.indexOf('*');
      ind[3] = str.indexOf('/');
      ind[4] = str.indexOf('(');
      ind[5] = str.indexOf(')');
      if(ind[1] == 0) {
        Arrays.sort(ind);
        int t;
        for(t = 0;t <6;t++) {
          if(ind[t] >= 0)
            break;
        }
        int r = ind[t+1];
        exp[i] = str.substring(0,r);
        i++;
        exp[i] = str.substring(r,r+1);
        str = str.substring(r+1);
      }else if(((ind[1]-ind[4]) == 1) && (ind[4]==0)) {
        Arrays.sort(ind);
        int t ;
        for(t = 0;t <6;t++) {
          if(ind[t] >= 0)
            break;
        }
        int r = ind[t+1];
        exp[i] = str.substring(0,1);
        i++;
        exp[i] = str.substring(1,r+2);
        i++;
        exp[i] = str.substring(r+2,r+3);
        str = str.substring(r+3);
      }else {
        Arrays.sort(ind);
        int t;
        for(t = 0;t <6;t++) {
          if(ind[t] >= 0)
            break;
        }
        if(t==6)
          break;
        index = ind[t];
        if(index!=0) {
          exp[i] = str.substring(0,index);
          i++;
        }
        exp[i] = str.substring(index,index+1);
        str = str.substring(index+1);
      }
    }
    int j = 0;
    int k = 0;
    for(; exp[j]!=null ;j++){}
    if(!exp[j-1].equals(")")) {
      exp[j]=str;
      str = "";
      k = j;
    }else {
      k = j-1;
    }
    String[] expp = new String[k+1];
    for(int t = 0; t < k+1;t++) {
      expp[t] = exp[t];
    }
    return expp;
    //System.out.println("分割的字符串:");
  }

2.中缀转后缀

 
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
private static String infToSuf(String[] exp) {
    String newStrs = "";
    //初始化栈
    Stack<String> stack = new Stack<>();
     /*
           判断并放入后缀表达式中:
       for循环遍历整个str进行判断
           循环结束若栈不为空全部出栈
     */
    int l = exp.length;
    for(int i = 0; i < l; i++) {
      if ((stack.empty()) && (exp[i].equals("+") || exp[i].equals("-") || exp[i].equals("*") || exp[i].equals("/"))) {
        stack.push(exp[i]);
      } else if (exp[i].equals("(")) {
        stack.push(exp[i]);
      } else if (exp[i].equals("*") || exp[i].equals("/")) {
        while (stack.peek().equals("*") || stack.peek().equals("/")) {
          newStrs = newStrs.concat(stack.pop()+" ");
          if(stack.isEmpty()) {
            break;
          }
        }
        stack.push(exp[i]);
      } else if (exp[i].equals("+") || exp[i].equals("-")) {
        while (!(stack.isEmpty())&&((stack.peek()).equals("*") || (stack.peek()).equals("/") || (stack.peek()).equals("+") || (stack.peek()).equals("-"))) {
          newStrs = newStrs.concat(stack.pop()+" ");
          if(stack.isEmpty()) {
            break;
          }
        }
        stack.push(exp[i]);
      } else if (exp[i].equals(")")) {
        int t = stack.search("(");
        for (int k = 1; k < t; k++) {
          newStrs = newStrs.concat(stack.pop()+" ");
        }
        String tstr = stack.pop();
      } else {
        newStrs = newStrs.concat(exp[i]+ " ");
      }
    }
    while (!stack.empty()) {
      if (!stack.peek().equals("(") || !stack.peek().equals(")")) {
        newStrs = newStrs.concat(stack.pop()+" ");
      } else if (stack.peek().equals("(") || stack.peek().equals(")")) {
        String tstr = stack.pop();
      }
    }
//   System.out.println("后缀:"+newStrs);
    return newStrs;
  }

3.后缀的计算

 
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
private static String sufToRes(String sufStr) {
  String[] exp = sufStr.split(" ");
  Stack<String> stack = new Stack<>();
  String Res = "";
  for(int i = 0;i < exp.length; i++) {
    if(!exp[i].equals("+") && !exp[i].equals("-") && !exp[i].equals("*") && !exp[i].equals("/")){
      stack.push(exp[i]);
    }else if(exp[i].equals("+")) {
      BigDecimal b2 = new BigDecimal(stack.pop());
      BigDecimal b1 = new BigDecimal(stack.pop());
      BigDecimal b3 = b1.add(b2);
      stack.push(b3.toString());
    }else if(exp[i].equals("-")) {
      BigDecimal b2 = new BigDecimal(stack.pop());
      BigDecimal b1 = new BigDecimal(stack.pop());
      BigDecimal b3 = b1.subtract(b2);
      stack.push(b3.toString());
    }else if(exp[i].equals("*")) {
      BigDecimal b2 = new BigDecimal(stack.pop());
      BigDecimal b1 = new BigDecimal(stack.pop());
      BigDecimal b3 = new BigDecimal(0);
      if(b1.compareTo(BigDecimal.ZERO)== 0|| b2.compareTo(BigDecimal.ZERO) == 0) {
        b3 = BigDecimal.ZERO;
      }else {
        b3 = b1.multiply(b2);
      }
      stack.push(b3.toString());
    }else if(exp[i].equals("/")){
      BigDecimal b2 = new BigDecimal(stack.pop());
      BigDecimal b1 = new BigDecimal(stack.pop());
      BigDecimal b3 = new BigDecimal(0);
      double d1 = b1.doubleValue();
      double d2 = b2.doubleValue();
      if(d1%d2 == 0){
        b3 = (b1.divide(b2));
        stack.push(b3.toString());
      }else {
        b3 = b1.divide(b2,10, RoundingMode.HALF_UP);
        stack.push(b3.toString());
      }
    }
  }
  Res = stack.pop();
  boolean flag = false;
  for (int m = 0; m < Res.length() - 1;m++) {
    if(Res.charAt(m) == '.'){
      flag = true;
    }
  }
  if(flag) {
    for(int m = Res.length()-1;m >= 0;m--) {
      if(Res.charAt(m) == '0'){
      }else {
        Res = Res.substring(0,m+1);
        break;
      }
    }
    if(Res.charAt(Res.length()-1) == '.') {
      Res = Res.substring(0,Res.length()-1);
    }
  }
  return Res;
}

开班信息

当前校区

北京校区
  • 北京校区
  • 上海校区
  • 广州校区
  • 沈阳校区
  • 杭州校区
  • 南京校区
  • 郑州校区
  • 成都校区
  • 深圳校区
  • 西安校区
  • 苏州校区
  • 深圳沙井
  • 深圳观澜
  • 深圳龙岗
  • 武汉校区
  • 西宁校区
  • 石家庄校区
  • 湖北咸宁
  • 广东惠州
  • 广东佛山

                    Copyright © 2007-2019 IT兄弟连教育 版权所有 京ICP备11018177号  京公网安备 11010802026987号