Java计算器最终版本

把上一版的计算器完善了下,目前可以支持加减乘除、多级括号及浮点运算,以下为源码:

计算器类:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 简单的计算器,支持加减乘除、多级括号及浮点运算
 * 
 * @author  Zero
 * @version 1.0
 * @Time    2017-02-17
 * @Site    Http://ay123.net
 */
public class Calculator {
    /**
     * Main function
     */
    public static void calculator(){
        Scanner input = new Scanner(System.in);
        StringBuilder s = new StringBuilder(
                                input.nextLine().replaceAll(" ", ""));
        StringBuilder subexpression;
        StringBuilder result;
        int           length = 0;
        
        while (true){
            subexpression = new StringBuilder(
                                    getSubexpression(s.toString()));
            String abc = getExpressionResult(subexpression.toString());
            result = new StringBuilder(abc);
            length = s.length();

            if (subexpression.length() == length)
                break;
            
            s.replace(s.indexOf("(" + subexpression.toString() + ")"), 
                      s.indexOf("(" + subexpression.toString() + ")") + 
                                  subexpression.length() + 2, 
                                  result.toString());
        }
        System.out.println("= " + result);
    }

    /**
     * Get subexpression inside the brackets
     * @param expression
     *             Expression need to calculate
     */
    public static String getSubexpression(String expression){
        StringBuilder s = new StringBuilder(expression);
        
        while (true){
            Pattern pattern = Pattern.compile(
                                "\\(([a-z0-9\\+\\-\\*\\/\\.]*?)\\)");
            Matcher matcher = pattern.matcher(s.toString());
            StringBuilder sb;
            if (matcher.find()){
                sb = new StringBuilder(matcher.group(1));
                s = new StringBuilder(sb.toString());
            }
            else
                break;
        }
        return s.toString();
    }
    /**
     * Calculate the expression's result
     * @param  expression
     *             Expression need to calculate
     */
    public static String getExpressionResult(String expression){
        StringBuilder subexpression = new StringBuilder(expression);
        StringBuilder result        = new StringBuilder("");
        StringBuilder subresult     = new StringBuilder("");
        int currentOperate          = 0;
        Pattern pattern;
        Matcher matcher;
        String[] operatorPriority = {"(\\-*\\d+\\.*\\d*)(\\*|\\/)
                                        (\\-*\\d+\\.*\\d*)", 
                                      "(\\-*\\d+\\.*\\d*)(\\+|\\-)
                                      (\\-*\\d+\\.*\\d*)"};

        while (true){
            // First check if any operator in the statement
            pattern = Pattern.compile("\\d+[\\+\\-\\*\\/]");
            matcher = pattern.matcher(subexpression);
            // Have match '+', '-', '*', '/'
            if (matcher.find()){
                pattern = Pattern.compile(operatorPriority[currentOperate]);
                matcher = pattern.matcher(subexpression);
                
                if (matcher.find()){
                    String a = matcher.group(1);
                    String b = matcher.group(2);
                    String c = matcher.group(3);
                    String abc = a + b + c;
                    double i = 0;
                    
                    switch (b){
                    case "*":
                        i = Double.parseDouble(a) * Double.parseDouble(c);
                        break;
                    case "/":
                        checkIfZero(c);
                        i = Double.parseDouble(a) / Double.parseDouble(c);
                        break;
                    case "+":
                        i = Double.parseDouble(a) + Double.parseDouble(c);
                        break;
                    case "-":
                        i = Double.parseDouble(a) - Double.parseDouble(c);
                        break;
                    }
                    subresult = subexpression.replace(
                                subexpression.indexOf(abc), 
                                subexpression.indexOf(abc) + abc.length(), 
                                String.format("%.2f", i));
                }
                else
                    currentOperate =1;
            }
            else
                break;
        }
        return subresult.toString();
    }
    /**
     * Check if the dividor is 0
     * @param  expression
     *             Expression need to calculate
     */
    public static void checkIfZero(String s){
        if (s.equals("0")){
            System.out.println("Dividor can't be 0!");
            return;
        }
    }
}

 

调用:

public class Main {
    public static void main(String[] args) {
        Calculator.calculator();
    }
}

 

运行结果:

 

版权声明:
作者:bin
链接:https://ay123.net/mystudy/550/
来源:爱影博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
Java计算器最终版本
把上一版的计算器完善了下,目前可以支持加减乘除、多级括号及浮点运算,以下为源码: 计算器类: import java.util.Scanner; import java.util.regex.Matche……
<<上一篇
下一篇>>