看了一些网上的代码,感觉多少有点问题,有的不能计算浮点数,有的不能计算多位数,或者没办法保证乘除法在加减法的前面,或者不能与负数进行混合运算。
我实现的如下:
特点是:在按“=”之前智能预算结果显示,点击按钮,按钮颜色变化
思路是:将输入的中缀表达式转换成后缀表达式进行计算
难点是:带负数的四则混合运算,以及智能预算显示(这一部分容易出问题)
当然最后要记得负0的处理还是为0,除以0提示不能除以0
源码地址:GitHub - liuchenyang0515/Simple_Intelligent_fault---tolerant_calculator: 简易智能容错计算器
如演示图不能正常播放,请刷新网页
简易智能容错计算器示意图(模拟我的华为手机界面和效果):
这里将中缀表达式转换为后缀表达式然后计算出结果的java代码贴出来,android代码见上面地址:
importjava.text.DecimalFormat; importjava.util.LinkedList; importjava.util.Queue; importjava.util.Scanner; importjava.util.Stack; publicclassTest { privatestaticStringBuilderstr; publicstaticvoidmain(String[] args) { Scannercin=newScanner(System.in); Strings=cin.next(); cin.close(); str=newStringBuilder(s); DecimalFormatdf=newDecimalFormat("###.##############"); Stringnum=null; try { doubled=calculate(); if (Double.isNaN(d) ||Double.isInfinite(d)) { System.out.println("不能除以0"); } else { num=df.format(d); } } catch (Exceptione) { System.out.println("错误!"); } System.out.println("-0".equals(num) ?"0" : num); } privatestaticdoublecalculate() { Queue<String>q=getPostfixExpression(); // 中缀表达式转为后缀表达式returncalculatePostfixExpression(q); } privatestaticdoublecalculatePostfixExpression(Queue<String>queue) { Stack<Double>stack=newStack<>(); intlen=queue.size(); doublenum1=0.0, num2=0.0, num3=0.0; for (inti=0; i<len; ++i) { Strings=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); } } returnstack.peek(); } // 获得后缀表达式publicstaticQueue<String>getPostfixExpression() { Stack<Character>stack=newStack<>(); intlen=str.length(); StringBuilderstrNum=newStringBuilder(); Queue<String>queue=newLinkedList<>(); chartemp=' '; for (inti=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()) { chartop=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()) { chartop=stack.peek(); queue.add(top+""); stack.pop(); } } returnqueue; } privatestaticbooleanisOperator(Strings) { returns.equals("+") ||s.equals("-") ||s.equals("*") ||s.equals("/"); } privatestaticintgetPriority(chartop) { if (top=='+'||top=='-') return1; return2; // 只有加减乘除 } }
运行结果示例:
========================Talk is cheap, show me the code========================