看了一些网上的代码,感觉多少有点问题,有的不能计算浮点数,有的不能计算多位数,或者没办法保证乘除法在加减法的前面,或者不能与负数进行混合运算。

我实现的如下:

特点是:在按“=”之前智能预算结果显示,点击按钮,按钮颜色变化

思路是:将输入的中缀表达式转换成后缀表达式进行计算

难点是:带负数的四则混合运算,以及智能预算显示(这一部分容易出问题)

当然最后要记得负0的处理还是为0,除以0提示不能除以0

 

源码地址:https://github.com/liuchenyang0515/Simple_Intelligent_fault---tolerant_calculator

 

如演示图不能正常播放,请刷新网页

简易智能容错计算器示意图(模拟我的华为手机界面和效果):

 

 

这里将中缀表达式转换为后缀表达式然后计算出结果的java代码贴出来,android代码见上面地址:

import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;

public class Test {

    private static StringBuilder str;

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        String s = cin.next();
        cin.close();
        str = new StringBuilder(s);
        DecimalFormat df = new DecimalFormat("###.##############");
        String num = null;
        try {
            double d = calculate();
            if (Double.isNaN(d) || Double.isInfinite(d)) {
                System.out.println("不能除以0");
            } else {
                num = df.format(d);
            }
        } catch (Exception e) {
            System.out.println("错误!");
        }
        System.out.println("-0".equals(num) ? "0" : num);
    }

    private static double calculate() {
        Queue<String> q = getPostfixExpression(); // 中缀表达式转为后缀表达式
        return calculatePostfixExpression(q);
    }

    private static double calculatePostfixExpression(Queue<String> queue) {
        Stack<Double> stack = new Stack<>();
        int len = queue.size();
        double num1 = 0.0, num2 = 0.0, num3 = 0.0;
        for (int i = 0; i < len; ++i) {
            String s = queue.poll();
            if (!isOperator(s)) {
                stack.push(Double.valueOf(s));
            } else {
                num2 = stack.pop();
                num1 = stack.pop();
                switch (s) {
                case "+":
                    num3 = num1 + num2;
                    break;
                case "-":
                    num3 = num1 - num2;
                    break;
                case "*":
                    num3 = num1 * num2;
                    break;
                case "/":
                    num3 = num1 / num2;
                    break;
                }
                stack.push(num3);
            }
        }
        return stack.peek();
    }

    // 获得后缀表达式
    public static Queue<String> getPostfixExpression() {
        Stack<Character> stack = new Stack<>();
        int len = str.length();
        StringBuilder strNum = new StringBuilder();
        Queue<String> queue = new LinkedList<>();
        char temp = ' ';
        for (int i = 0; i < len; ++i) {
            temp = str.charAt(i);
            if (temp >= '0' && temp <= '9' || temp == '.') {
                strNum.append(temp);
            } else {
                if (i == 0 || isOperator(str.charAt(i - 1) + "")) {
                    // 考虑负数的情况,比如乘以除以负数
                    strNum.append(temp);
                    continue;
                }
                queue.add(strNum.toString()); // 数字进队列
                strNum.setLength(0);
                if (stack.isEmpty()) {
                    stack.push(temp);
                } else {

                    while (!stack.isEmpty()) {
                        char top = stack.peek();
                        if (getPriority(top) >= getPriority(temp)) {
                            queue.add(top + "");
                            stack.pop();
                        } else {
                            break;
                        }
                    }
                    stack.push(temp);
                }
            }
        }
        queue.add(strNum.toString()); // 数字进队列
        if (stack.isEmpty()) {
            stack.push(temp);
        } else {
            while (!stack.isEmpty()) {
                char top = stack.peek();
                queue.add(top + "");
                stack.pop();
            }
        }
        return queue;
    }

    private static boolean isOperator(String s) {
        return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
    }

    private static int getPriority(char top) {
        if (top == '+' || top == '-')
            return 1;
        return 2; // 只有加减乘除
    }
}

运行结果示例:

========================Talk is cheap, show me the code========================