Implement arithmetic code in Java _java

Source: Internet
Author: User
Tags arithmetic stringbuffer

The idea of the

code is to compute each of the smallest calculated cells by regular judgment. The following is code:

Import Java.math.BigDecimal;
Import Java.util.regex.Matcher;

Import Java.util.regex.Pattern; /** * Calculator Tool class * @author Shuqi * @date 2015-7-23 * @version since 1.0/public class Calculatorutil {public Stati C BigDecimal Arithmetic (string exp) {if (!exp.matches ("\\d+")) {String result = PARSEEXP (exp). ReplaceAll ("[\\[\\]
      ]", "");
    Return to new BigDecimal (result);
    }else{return new BigDecimal (exp); }/** * Minimum count unit */private static String minexp= "^ (\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+)/\)) [\\+\\-\\*\\/] ((\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+)/\))
  $";
  /** * operation with no parentheses * * private static String noparentheses= "^[^\\ (\)]+$"; /** * Matching multiplication or division/private static String prioroperatorexp= "((\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+)/\)) [\\*\\/] ((\\d+ (\\.\\d+)?) |
  (\\[\\-\\d+ (\\.\\d+))) "; /** * Matching addition and subtraction/private static String operatorexp= "((\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+)/\)) [\\+\\-] ((\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+))) ";
  
  /** * matches only one bracket/private static String minparentheses= "\ ([^\\ (\)]+\\)"; /** * Analytic computation arithmetic expression, example: 3+4 *2-22)/2*3 * @param expression * @return/private static String Parseexp (Strin G expression) {//method to enter the first substitution space, in the removal operation on both sides of the () number Expression=expression.replaceall ("\\s+", ""). ReplaceAll ("^\\ ([^\\ (\)]+) \
    
    \) $ "," "$");
      The minimum expression evaluates to an if (Expression.matches (minexp)) {String result=calculate (expression);
    return double.parsedouble (Result) >=0?result: "[" +result+] ";
      ///Calculate Arithmetic if (expression.matches (noparentheses)) {pattern patt=pattern.compile (prioroperatorexp) without parentheses;
      Matcher mat=patt.matcher (expression);
        if (Mat.find ()) {String tempminexp=mat.group ();
      Expression=expression.replacefirst (Prioroperatorexp, Parseexp (tempminexp));
        }else{Patt=pattern.compile (OPERATOREXP);
        
        Mat=patt.matcher (expression); if (Mat.find ()) {String tempminexp=Mat.group ();
        Expression=expression.replacefirst (Operatorexp, Parseexp (tempminexp));
    } return Parseexp (expression);
    ///Calculate the arithmetic pattern patt=pattern.compile (minparentheses) with parentheses;
    Matcher mat=patt.matcher (expression);
      if (Mat.find ()) {String tempminexp=mat.group ();
    Expression=expression.replacefirst (minparentheses, Parseexp (tempminexp));
  return parseexp (expression); /** * Calculates the minimum unit arithmetic expression (two digits) * @param exp * @return/private static String calculate (string exp) {EXP
    =exp.replaceall ("[\\[\\]]", "" ");
    String Number[]=exp.replacefirst ("(\\d) [\\+\\-\\*\\/]", "$"). Split (",");
    BigDecimal number1=new BigDecimal (number[0]);
    BigDecimal number2=new BigDecimal (number[1]);
    
    BigDecimal Result=null;
    String Operator=exp.replacefirst ("^.*\\d ([\\+\\-\\*\\/]). +$", "$");
    if ("+". Equals (operator)) {result=number1.add (number2); }else if ("-". Equals (operator)) {Result=nUmber1.subtract (NUMBER2);
    }else if ("*". Equals (operator)) {result=number1.multiply (number2); }else if ("/". Equals (operator)) {//The second parameter is precision, and the third is a four-color five-in mode Result=number1.divide (Number2,5,bigdecimal.round_ceilin
    G);
  Return result!=null?result.tostring (): null;

 }
  
}

The code was originally a blog, the original code is not commented and there are bugs, I slightly revised a ha added a comment. Make a note here for your convenience

Another token of respect for the original author, attached to the original code

/** * Arithmetic expression calculation * @author Penli * * */public class Arithmetic {public static void main (String args[]) {SYSTEM.OUT.P
 Rintln (Arithmetic ("2.2+ (3+4) *2-22)/2*3.2");
 public static double Arithmetic (string exp) {string result = PARSEEXP (exp). ReplaceAll ("[\\[\\]]" "" ";
 return double.parsedouble (Result); /** * Analytic calculation of arithmetic expression, example: 3+4 (*2-22)/2*3 * @param expression * @return/public static string Parseexp (String expre ssion) {//string numberreg= "^ (?! 0) \\d+ (\\.\\d+ (? <!0)) |
 (0\\.\\d+ (? <!0)) $ ";
 Expression=expression.replaceall ("\\s+", ""). ReplaceAll ("^\\ ((. +) \) $", "$");
 String checkexp= "\\d"; String minexp= "^ (\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+)/\)) [\\+\\-\\*\\/] ((\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+)/\))
 $";
  
  The minimum expression evaluates to an if (Expression.matches (minexp)) {String result=calculate (expression);
 return double.parsedouble (Result) >=0?result: "[" +result+] ";
 }//Calculate arithmetic String noparentheses= "^[^\\ (\)]+$" without parentheses; String prioroperatorexp= "((\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+)) [\\*\\/] (\\d+ (\\.\\d+)?) |
 (\\[\\-\\d+ (\\.\\d+))) "; String operatorexp= "((\\d+ (\\.\\d+)?) | (\\[\\-\\d+ (\\.\\d+)/\)) [\\+\\-] ((\\d+ (\\.\\d+)?) |
 (\\[\\-\\d+ (\\.\\d+))) ";
  if (Expression.matches (noparentheses)) {pattern patt=pattern.compile (PRIOROPERATOREXP);
  Matcher mat=patt.matcher (expression);
  if (Mat.find ()) {String tempminexp=mat.group ();
  Expression=expression.replacefirst (Prioroperatorexp, Parseexp (tempminexp));
  }else{Patt=pattern.compile (OPERATOREXP);
  
  Mat=patt.matcher (expression);
   if (Mat.find ()) {String tempminexp=mat.group ();
  Expression=expression.replacefirst (Operatorexp, Parseexp (tempminexp));
 } return Parseexp (expression);
 //To compute the parenthesized arithmetic String minparentheses= "\ [^\\ (\)]+\\)";
 Pattern Patt=pattern.compile (minparentheses);
 Matcher mat=patt.matcher (expression);
  if (Mat.find ()) {String tempminexp=mat.group ();
 Expression=expression.replacefirst (minparentheses, Parseexp (tempminexp)); Return Parseexp (EXpression); /** * Calculates the minimum unit arithmetic expression (two digits) * @param exp * @return/public static String calculate (String exp) {Exp=exp.replaceal
 L ("[\\[\\]]", "" ");
 String Number[]=exp.replacefirst ("(\\d) [\\+\\-\\*\\/]", "$"). Split (",");
 BigDecimal number1=new BigDecimal (number[0]);
 BigDecimal number2=new BigDecimal (number[1]);
 
 BigDecimal Result=null;
 String Operator=exp.replacefirst ("^.*\\d ([\\+\\-\\*\\/]). +$", "$");
 if ("+". Equals (operator)) {result=number1.add (number2);
 }else if ("-". Equals (operator)) {result=number1.subtract (number2);
 }else if ("*". Equals (operator)) {result=number1.multiply (number2);
 }else if ("/". Equals (operator)) {result=number1.divide (number2);
 Return result!=null?result.tostring (): null;

 }
}

Finally to share a Netizen's implementation method, personal feeling is also very good

Import Java.util.Stack; /** * Use the stack, the arithmetic class * with two stacks to achieve operator first, a stack to save the data to be calculated numstack, one to save the calculation of the priority pristack * * * basic algorithm implementation of the idea is: with the currently obtained operator and the Pristack stack top Operator comparison precedence: If above, because will first operation, put into the top of the stack; * If equal, because appear in the back, so will calculate after, so stack top elements out of the stack, take the operand operation; * If less than, the same, remove the stack top element operation, the result into the operand stack. Individual priority ' (' > ' + ' = '/' > ' + ' = '-' > ') ' * */public class Operate {private stack<character> P Ristack = new stack<character> ()//Operation Fu Yi private stack<integer> numstack = new stack<integer> ();   
  /operand stack/** * Pass in the string that needs to be parsed, return the result (here because of the time problem, omit the validity verification) * @param str needs to perform the technical expression * @return Calculation result * * public int caculate (String str) {//1. Determine if there are any illegal characters in string temp;//used to temporarily hold read characters//2. Loop Start parsing string , when the string is parsed and the symbol stack is empty, the calculation completes stringbuffer tempnum = new StringBuffer ();//To temporarily hold the numeric string (when multiple digits) StringBuffer string = new StringBuffer (). append (str);//To save, improve efficiency while (String.Length ()!= 0) {temp = string.substring (0   
      , 1); String. Delete (0, 1); Judge Temp, when temp is an operator if (!isnum (temp)) {//1. At this point the tempnum is the number that needs to be manipulated, the number taken out, the stack is pressed, and the tempnum if (!) is emptied.    
          ". Equals (Tempnum.tostring ())) {//when the first symbol of an expression is a bracket int num = Integer.parseint (tempnum.tostring ()); 
          Numstack.push (num);   
        Tempnum.delete (0, Tempnum.length ()); Compare priority with the currently obtained operator and the stack top operator: If above, because it will first operation, put into the top of the stack, if equal to, because appear in the back, so after the calculation, so stack top elements out of the stack, take the operand operation;//if less than, the same, remove the stack top element operation,   
   
        Put the result into the operand stack. Determines the current operator and stack top element precedence, takes out the element, evaluates (because the priority may be less than the top of the stack, is smaller than the second element, and so on, and needs to be cycled) while (!compare (Temp.charat (0)) && (!pri   
          Stack.empty ()) {int a = (int) numstack.pop ();//the second operand int b = (int) numstack.pop (); The first one counts.   
          Char ope = Pristack.pop (); int result = 0;//results switch (ope) {//If it is a plus or minus sign, case ' + ': Resul   
            T = B + A; Put the results of the operation into the operand stack numstack.push (resuLT);   
          Break   
            Case '-': result = b-a;   
            Putting the operation results into the operand stack numstack.push (result);   
          Break   
            Case "*": result = b * A;   
            Putting the operation results into the operand stack numstack.push (result);   
          Break   
            Case '/': results = b/a;//The operation result into the operand stack numstack.push.   
          Break   
          }//Determine the priority of the current operator and the top element of the stack, if high, or below the level, after the calculation, the current operation symbol is put into operation Fu Yi if (Temp.charat (0)!= ' # ') {   
          Pristack.push (New Character (Temp.charat (0)));   
            if (Temp.charat (0) = = ') ' {//when the stack top is ' (', while the current element is ') ', it is enclosed in parentheses to finish, and remove the bracket pristack.pop ();   
          Pristack.pop (); I//when the characters (number) Tempnum = tempnum.append (temp);//The number that will be read is counted after the number read out (when it is not   
  Single digit Time)} return Numstack.pop (); }/** * To determine if the incoming characters are 0-9 digits 
   * @param str * Incoming String * @return/Private Boolean isnum (String temp) {return   
  Temp.matches ("[0-9]"); /** * Compares the current operator with the top element operator precedence, returns True if it is higher than the top of the stack, or returns false * * @param str need to compare the character * @return ratio   
      The result is a higher precedence than the top of the stack, and false represents a lower priority than the top element of the stack/private Boolean compare (char str) {if (Pristack.empty ()) {   
    When empty, it is obvious that the current priority is the lowest and returns a high return true;   
    Char last = (char) pristack.lastelement ();   
    If the top of the stack is ' (obviously, the lowest priority, ') ' is not possible for the top of the stack.   
    if (last = = ' (') {return true;   
      Switch (str) {case ' # ': Return false;//Terminator case ' ('://' (' highest precedence, apparently returns true   
    return true;   
    Case ') ': ' The lowest priority, return false;   
      Case ' * ': {//'/' priority is only greater than ' +-' high if (last = = ' + ' | | | last = = ') return true;   
    else return false; Case '/': {if (last = = ' + '||   
      last = = '-') return true;   
    else return false;   
    //' +-' is the lowest, always returns false case ' + ': return false;   
    Case '-': return false;   
  return true;   
    public static void Main (String args[]) {Operate Operate = new Operate ();    
    int t = operate.caculate ("(3+4* (4*10-10/2) #");   
  System.out.println (t);    }   
   
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.